嵌套的猫鼬充满了希望 [英] Nested mongoose populate with promises
问题描述
我正在尝试填充如下所示的模型:
var Org = new mongoose.Schema({
_id: {type: String, unique:true}, //this will be the org code
name: String,
level: String,
children: [{type: String, ref: 'Org'}]
});
//Orgs have children orgs, which themselves can have children orgs at N levels
考虑到一个组织,我想填充它的孩子们,以及它的孩子们的孩子,等等.我可以在N = 2个级别上完成此操作,例如:
req.Model.findOne({_id: id}).populate('children').exec(function(err, doc){
if (err){
return next(err);
}
req.Model.populate(doc, {path: 'children.children'}, function(err, doc){
if(err){
return next(err);
}
return res.json(doc);
});
});
几个小时以来,即使在N = 2的情况下,我也一直在尝试使用Promise来完成上述任务.我认为,对于N = *级别,使用猫鼬具有内置实现的承诺会更清洁.
For hours now I have been trying to accomplish the above using promises, even at N=2. I think that for N = * levels, It would be cleaner to do so with promises which mongoose has a built in implementation of.
req.Model.findOne({_id: id}).populate('children').exec()
.then(function (doc){
if(!treeView) {
return doc;
}
return req.Model.populate(doc, {path: 'children.children'});
})
.then(function (doc){
return res.json(doc);
},function(err){
return next(err);
});
// treeView is a query string that lets me know that I need to populate the refs
我认为它应该按以下方式工作:
- exec()返回一个promise,我在对then()的第一次调用中就开始处理它
- 如果treeView为false,我返回doc,这被视为原始诺言的解决方案,因此调用了第二个then()处理函数.这确实发生了.
- 如果treeView为true,则对Model.populate的调用将返回另一个Promise,第二次对then()的调用也将处理该Promise.
我遇到此错误:
{
"status": "error",
"serverTimestamp": "2014-07-24T18:23:02.974Z",
"message": "\"function\" == \"undefined\""
}
我知道它到达第二个then()错误处理程序,因为我已经登录到控制台进行验证,但是我无法弄清楚为什么会这样.一旦使它起作用,我将尝试使其适用于N = *级,我想这将涉及递归地创建更多的Promise.我在这里看到了许多相关的问题,但并不是我真正需要的.
I know it gets to the second then()'s error handler, because I have logged out to the console to verify, but I cannot figure out why this is happening. Once I can get this to work, I will try to make it work for N=* levels, which I imagine would involve creating more promises recursively. I have seen many questions here related, but not exactly what I needed.
任何帮助将不胜感激.
Any help is greatly appreciated.
推荐答案
我能够使用mongoose模型返回的Mongoose许诺使嵌套的子文档在MongooseJS v4.1中填充工作.无需使用其他Promise库.
I was able to make nested subdocument populate work in MongooseJS v4.1 using the Mongoose promise returned from the mongoose model. No need to use another promise library.
var fuelOrderId = req.params.fuelOrderId;
fuelOrderModel.findById(fuelOrderId).populate('aircraftId')
.then(function(order){
return fuelOrderModel.populate(order,
{path: 'aircraftId.aircraftContacts',
model: 'aircraftContactModel'});
})
.then(function(result){
res.json({
fuelOrder: result,
status: 1
});
},function(err){
console.error(err);
res.json({err: err, status: 0});
})
编辑请考虑使用.catch()
而不是第二个功能来处理错误. mpromise现在支持.catch()
.
Edit consider using .catch()
instead of a second function for errors. mpromise now supports .catch()
.
这篇关于嵌套的猫鼬充满了希望的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!