javascript - 无法从数据库获取数据

标签 javascript node.js mongodb mongoose

我正在尝试使用真/假条件从 mongoDB 获取一些数据

这是回调函数:

module.exports.getAllTeachersByValidation = function (condition, fields, options, callback){
    const query =  {
      account: {
          valid: condition
      }
    };
    Teacher.find(query, fields, options, callback);
};

这是方案:

const teacherSchema = mongoose.Schema({
    account: {
        username: {
            type: String,
            required: true,
            unique: true,
            lowercase: true
        },
        password: {
            type: String,
            required: true
        },
        valid: {
            type: String,
            enum: ["true","false"],
            required: true,
            lowercase: true
        }
    },

代码:

const condition = req.query.condition;
    const ret_values = "_id "
            + "ID "
            + "account.username "
            + "account.valid "
            + "name "
            + "communication.email "
            + "communication.phone";
    if(typeof condition !== 'undefined'){
        console.log("Sending teachers by validation: " + condition);
        Teacher.getAllTeachersByValidation(condition.toLowerCase(), ret_values, {}, (error, teachers) => {
            if (error) throw error;
            if(teachers){
                return res.json({
                    success: true,
                    teachers
                });
            }else{
                return res.json({
                    success: false,
                    msg: "Error retrieving teachers",
                    error: "No teacher to be found"
                });
            }
        });
    }

我尝试过当 valid 为 String 类型和当 valid 为 Boolean 类型时,但结果总是得到一个空的教师数组(成功:true)

有人可以解释一下为什么 .find() 不返回数组吗?或者我的问题出在哪里?

当我不使用条件字段时,它会返回所有教师(包括当 valid 为 false/true 时)

最佳答案

在这种情况下您的查询不正确

而不是:

const query =  {
      account: {
          valid: condition
      }
};

用途:

const query =  {
      "account.valid": condition
};

在第一种情况下,您仅查询帐户子文档恰好为{"valid": "true"}的文档,而没有用户名密码

更多信息请点击:https://docs.mongodb.com/manual/tutorial/query-embedded-documents/

关于javascript - 无法从数据库获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43596357/

相关文章:

javascript - 从 Canvas 保存图像时缺少扩展名

node.js - 聚合方法未按预期工作

node.js - 有没有办法避免使用 Mongoose 进行硬编码?

javascript - 如何在 UIWebview 中启用 JavaScript

javascript - 在 IndexedDB 中的对象中索引数组值

javascript - Vue <template> 标记在迭代列表时未按预期运行

javascript - 使用 Bluebird 进行异步 Promise 处理

node.js - 使用 next.js,为什么我突然开始看到找不到模块 : Error: Can't resolve 'fs' ?

javascript - Azure 上的 Nodejs 返回 403

javascript - "Sending request"在 Postman 上加载 Get 请求