我是 Mongoose 的新手。 这是我的场景:
var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
children: [childSchema]});
var Parent = mongoose.model('Parent', parentSchema);
假设我已经创建了一个带有子项的父项“p”,并且我正在查询“p”,使用
var query = Parent.find({"_id":"562676a04787a98217d1c81e"});
query.select('children');
query.exec(function(err,person){
if(err){
return console.error(err);
} else {
console.log(person);
}
});
我需要在异步函数之外访问 person 对象。关于如何执行此操作的任何想法?
最佳答案
Mongoose 的 find()
方法是 asynchronous 这意味着你应该使用一个回调,你可以包装来自 find()
的查询 方法。例如,在您的情况下,您可以将回调定义为
function getChildrenQuery(parentId, callback){
Parent.find({"_id": parentId}, "children", function(err, docs){
if (err) {
callback(err, null);
} else {
callback(null, docs);
}
});
}
然后你可以这样调用:
var id = "562676a04787a98217d1c81e";
getChildrenQuery(id, function(err, children) {
if (err) console.log(err);
// do something with children
children.forEach(function(child){
console.log(child.name);
});
});
您可以采用的另一种方法是 promise ,其中 exec()
方法返回一个 Promise ,因此您可以执行以下操作:
function getChildrenPromise(parentId){
var promise = Parent.find({_id: parentId}).select("children").exec();
return promise;
}
然后,当你想获取数据时,你应该将其设为异步:
var promise = getChildrenPromise("562676a04787a98217d1c81e");
promise.then(function(children){
children.forEach(function(child){
console.log(child.name);
});
}).error(function(error){
console.log(error);
});
关于node.js - 如何在 mongoose 中保存从 query.exec() 函数返回的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33244506/