I am working on a node.js which has multiple steps with Mongo:
- Get a document
- Push a subdocument into the subarray and save
- Do an aggregation framework query to get the inserted subdocument
- Return it to the calling function
My function:
addItem(itemId, data1, data2) {
return new Promise(function(resolve, reject) {
let item = Model.findOne({'_id': new ObjectID(itemId)});
resolve(item);
}).then(function(item) {
// STEP 2
const id = new ObjectID();
item.stuff.push({data1: .... })
item.save();
return { item: item, id: id }
}).then(function(res) {
return Model.aggregate([ .... ])
}).then(function(res) {
return res;
})
}
The problem is, I call my function addItem,
addItem(itemId, data1, data2).then(res => { PROBLEM })
where PROBLEM returns the call definition to my aggregation framework.
Example:
console.log(PROBLEM);
Aggregate {
_pipeline: [
.. items
],
_model: Model {},
options: {}
}
How do I fix it so my aggregation framework returns data? I think it has something to do w/ STEP 2, especially considering .save() returns a Promise
findOneis async, it does not return the document in the way you use it.item.save()is asynchronous too, but you don't wait it to finish.Model.aggregateshould be followed byexec()to actually fetch data, and it is async too.