gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:28:34 25 4
gpt4 key购买 nike

我正在尝试使用真/假条件从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com