2017-04-24 52 views
0

我想用真/假條件廣東話從數據庫中提取數據

這裏來從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" 
       }); 
      } 
     }); 
    } 

我試過有效的時候是一個字符串類型,當有效的時候是一個布爾類型,但我總是得到一個空教師的數組作爲結果(成功:真)

有人可以解釋爲什麼.find()不返回數組?或者我的問題在哪裏?

當我不使用條件字段它返回所有教師(包括當有效是假/真)

回答

1

您的查詢是不是在這種情況下,正確的

相反的:

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

用途:

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

在第一種情況下,你只能查詢文件衛生組織Ë帳戶子文檔正是{ 「有效」: 「真正的」},沒有用戶名密碼

更多的信息在這裏:https://docs.mongodb.com/manual/tutorial/query-embedded-documents/