node.js - 如何在 mongoose 中保存从 query.exec() 函数返回的对象

标签 node.js mongodb mongoose

我是 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/

相关文章:

node.js - mongodb/mongoose findMany - 查找 ID 列在数组中的所有文档

node.js - 以下划线为前缀的属性的 eslint 问题

javascript - 中止 doc.save() 内的 mongooseJS 保存过程

node.js - 发布具有不同依赖项的两个版本的 npm 模块

javascript - mongodb 文章.长度未定义

node.js - 在 Mongoose 更新查询中运行自定义验证

node.js - 直接从 URL 查询字符串提供的 mongo 查询有多危险?

arrays - NodeJS : Extracting duplicates from Array

javascript - TypeScript:将字符串转换为对象

javascript - 函数参数中变量周围的花括号是什么意思