【发布时间】:2019-05-23 09:48:59
【问题描述】:
我有两个模式教师和学生
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.findOne 一起等待用户。
这样
let student = await Student.findOne({"email":students.email})
结果我得到了一个 Query 对象。
任何人都可以建议任何方式在循环中使用 await 或任何其他方式来获得我想要的输出吗?
如果我在循环中的任何地方使用 await,节点就会崩溃,因此在其他地方回答的在循环中使用 async/await 的解决方案并不能解决我的问题。
【问题讨论】:
-
@DragonBorn 我已经尝试了该帖子中人们回答的解决方案,但是如果我在循环中的任何地方使用 await ,节点就会崩溃,所以它不能解决我的问题。
-
当它崩溃时你得到了什么错误,你使用
for of而不是forEach? -
@DragonBorn 我收到了这个错误:TypeError: this.$__path is not a function
-
您能否包含您在其他帖子中尝试过的代码,该代码给出了此错误。请包含从您的
async开始的整个函数。
标签: node.js mongodb express mongoose foreach