【发布时间】: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