Node.js 在forEach循环中获取Mongo数据库值
我有两个老师和学生Node.js 在forEach循环中获取Mongo数据库值,node.js,mongodb,express,mongoose,foreach,Node.js,Mongodb,Express,Mongoose,Foreach,我有两个老师和学生 StudentSchema = new mongoose.Schema({ email:{type:String, index: {unique:true}} name:{type:String}, marks:[{ subject:{type:String, marks:{type:Number} }] }) TeacherSchema = new mongoose.Schema({ email:{type:String, index: {unique:true}} n
StudentSchema = new mongoose.Schema({
email:{type:String, index: {unique:true}}
name:{type:String},
marks:[{
subject:{type:String,
marks:{type:Number}
}]
})
TeacherSchema = new mongoose.Schema({
email:{type:String, index: {unique:true}}
name:{type:String},
students:[{
email:{type:String},
registerationDate:{type:Date}
}]
})
我有一个API,在那个里我可以得到老师的电子邮件id,并且必须用注册给那个老师的学生的分数和名字来回复
对于这个,我使用这个代码
var teacher = await Teacher.findOne({"email":req.body.email})
teacher.students.forEach(function(students){
let student = Student.findOne({"email":students.email})
console.log(student) // to watch the result
})
我想在Student变量中获得完整的Student模式,以便使用Student的数据
但是我没有得到想要的输出,因为我不能和Student.findOne一起等待用户
像这样
let student = await Student.findOne({"email":students.email})
我得到一个查询对象作为结果
有人能建议使用wait-in-the-loop或其他方法来获得我想要的输出吗
如果我在循环中的任何地方使用wait,节点就会崩溃,因此在其他地方回答使用async/wait in循环的解决方案并不能解决我的问题。您可以使用mongoose的find函数代替forEach,如下所示:
teacher.find({}, function (err, teachers) {
// now you can use teachers.forEach here for getting students
console.log(teachers.students)
});
我想你是想让所有的老师和他们的学生在一起。根据我对你问题的理解,这应该会有所帮助
Teacher.find({}, (error, allTeachers) => {
if (error) {
// Handle Error
} else {
allTeachers.forEach(teacher=> {
let student = Student.findOne({"email":teacher.email})
});
}
})
注意:Mongoose查询没有本机同步API,但您可以链接查询 试试这个
Teacher.findOne({"email":req.body.email}, (err, teacher)=>{
if( !err ) {
let studentEmailIds = [];
teacher.students.forEach( (students) => {
studentEmailIds.push(students.email);
});
Student.find({'email': {"$in": studentEmailIds } }, (err, students)=>{
if(err){
//error handle
}else{
console.log(students)
//res.json(students);
}
});
}
})
不能在
forEach
循环中使用wait。您必须为..使用。。而不是循环
一个forEach
循环触发多个异步请求,但该函数随后立即返回。它不会等待您的承诺解决,而用于。。循环的
执行
将代码更改为:
for (let students of teacher.students) {
let student = Student.findOne({"email":students.email})
console.log(student) // to watch the result
});
可能是@DragonBorn的副本我已经尝试了该帖子中的人回答的解决方案,但是如果我在循环中的任何地方使用wait,节点就会崩溃,所以它并没有解决我的问题。当它崩溃时,你得到了什么错误?你使用了of的而不是forEach的吗?@DragonBorn我得到了这个错误:TypeError:this。$\uu path不是一个函数。你能包括你在另一篇文章中尝试的代码吗。请包含从您的异步开始的整个函数。我的节点一直在使用您的代码崩溃,而没有在if条件中显示错误消息。我犯了一个语法错误,现在已修复,您可以尝试它。它仍然会崩溃。我想这是因为我使用了teacher.findOne而不是teacher.findOne。试着改变一下。还有,当它崩溃时,你会得到什么错误?它不会显示任何错误,它会立即崩溃。学生应该在教师中,你能把调试放在评论行上,并把教师中的内容发送给我吗?我不明白你问的是哪一个,是我问题中的一个还是你答案中的一个?我的意思是尝试我的答案并观察教师。find({},函数(err,teachers){//现在您可以在这里使用teachers.forEach来获取学生控制台.log(teachers.students)});节点崩溃,没有任何错误消息[nodemon]应用程序崩溃-正在等待文件更改,然后再启动。。。