How to save the object returned by query.exec () function in mongoose

I am new to mongoose. Here is my scenario:

var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
children: [childSchema]});
var Parent = mongoose.model('Parent', parentSchema);

Let's say I created a parent "p" with children, and I request "p" using

var query = Parent.find({"_id":"562676a04787a98217d1c81e"});
query.select('children');                                   
query.exec(function(err,person){                            
    if(err){                                                    
        return console.error(err);                               
    } else {                                                     
        console.log(person);                                     
    }
});                                                    

I need to access the person object outside the async function. Any idea on how to do this?

+4
source share
2 answers

The Mongoose method is asynchronous , which means you have to use a callback so that you can wrap the request from . For example, in your case, you can define a callback as find() find()

function getChildrenQuery(parentId, callback){
    Parent.find({"_id": parentId}, "children", function(err, docs){
        if (err) {
          callback(err, null);
        } else {
          callback(null, docs);
        }
    }); 
}

which you can call as follows:

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);
    });
});

, , - promises, exec() Promise, :

function getChildrenPromise(parentId){
   var promise = Parent.find({_id: parentId}).select("children").exec();
   return promise;
}

, , async:

var promise = getChildrenPromise("562676a04787a98217d1c81e");
promise.then(function(children){
    children.forEach(function(child){
        console.log(child.name);
    });
}).error(function(error){
    console.log(error);
});
+5

(= " ", ). node.js:

  • - , , .
  • Node.js , , , query.exec.
  • , query.exec, , .

... :

  • , , " "
  • , " "
0

Source: https://habr.com/ru/post/1612486/


All Articles