我正在尝试使用true / false条件从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类型,当有效是一个布尔类型时,但我总是得到一个空数组的教师作为结果(success:true)
有人可以解释为什么.find()不返回数组吗?或者我的问题在哪里?
当我不使用条件字段时,它会返回所有教师(包括有效时为false / true)
答案 0 :(得分:1)
在这种情况下,您的查询不正确
而不是:
const query = {
account: {
valid: condition
}
};
使用:
const query = {
"account.valid": condition
};
在第一种情况下,您只查询帐户子文档正好 {"有效":" true"} 的文档,没有用户名和密码。
此处提供更多信息:https://docs.mongodb.com/manual/tutorial/query-embedded-documents/