如何对forEach做出承诺?我想获得所有工作,但获得申请人的数据。我的Job模式已经有申请人ID,但是如何查询用户并在输出中合并他们的详细信息?
Job.find({}).then(result => {
result.forEach(obj =>{
const applicant_id = obj.applicant._id
if(applicant_id){
User.findOne({_id: applicant_id})
.then(user=>{
return res.json({
status: 1,
data: {
...obj,
applicant: {
...user
}
}
})
})
}
})
}).catch(err => {
if(err){
return res.status(400).send({
msg: err
})
}
})
我尝试过Promise,但我将用户合并到Job obj中,
Job.find({}).then(result => {
let promiseArray = []
result.forEach(obj =>{
const applicant_id = obj.applicant._id
if(applicant_id){
promiseArray.push(
User.findOne({_id: applicant_id}))
}
})
return Promise.all(promiseArray)
}).then(user => {
console.log(user)
//this work but this is only the user's data,
//I need it to be within obj which is Job data
})
答案 0 :(得分:0)
首先需要过滤结果中的项目以排除那些没有申请人ID的项目,然后将此数组映射到promises数组,最后将其传递给Promise.all
。这应该这样做:
Job.find({}).then(result => {
const promises = result
.filter(obj => obj.applicant._id)
.map(obj => {
const applicant_id = obj.applicant._id
return User.findOne({ _id: applicant_id })
.then(user => {
return res.json({
status: 1,
data: {
...obj,
applicant: {
...user
}
}
})
})
})
return Promise.all(promises)
}).catch(err => {
if (err) {
return res.status(400).send({
msg: err
})
}
})
答案 1 :(得分:0)
这是一个经过测试和运作的解决方案:
immutable