1

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

2
  • With so many steps you'd be better with async/await syntax. findOne is 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.aggregate should be followed by exec() to actually fetch data, and it is async too. Commented Jun 4, 2022 at 0:29
  • 1
    I figured it out (I posted my solution) I was doing the promise and the async / await backward. I'm trying to get used to this method, and definitely trying to avoid the "Pyramid of Doom" syntax. Commented Jun 4, 2022 at 3:12

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.