【问题标题】:Cant fetch data from the DataBase无法从数据库中获取数据
【发布时间】:2017-09-21 14:57:09
【问题描述】:

我正在尝试使用真/假条件从 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() 不返回数组吗?或者我的问题在哪里?

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

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

    代替:

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

    用途:

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

    在第一种情况下,您只查询 account 子文档正好是 {"valid": "true"} 的文档,没有 username密码

    更多信息在这里:https://docs.mongodb.com/manual/tutorial/query-embedded-documents/

    【讨论】:

      猜你喜欢
      • 2018-05-28
      • 2012-01-06
      • 2021-10-25
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      相关资源
      最近更新 更多