Home > Back-end >  Multiple MongoJS calls in Node.js
Multiple MongoJS calls in Node.js

Time:06-07

I am working on a node.js which has multiple steps with Mongo:

  1. Get a document
  2. Push a subdocument into the subarray and save
  3. Do an aggregation framework query to get the inserted subdocument
  4. 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

CodePudding user response:

Ok, so it looks like I did the Promise and async / await backwards.

The solution:

In Express, my endpoint:

app.post('/endpoint', (req, res) => {
    new Promise(resolve => {
        addMessage(currentUserId, chatId, msg).then(res => {
            console.log(res);
            res.sendStatus(codes.CREATED).send(res);
        });
    });
});

and my addMessage function:

addMessage = async function (userId, chatId, message) {
    let item = await Model.findOne({ .... });
    let id = new ObjectID();
    item.stuff.push({data1: .... });
    await item.save();
    let retval = await Model.aggregate([ .... ]);
    return retval;
}
  • Related