DB not updated without await infront of the method

Viewed 542

Hello I have following piece of code:

  async create(data) {
    const document = new this.productModel(data);

    const created = await document.save();

    this.userModel.findByIdAndUpdate(data.user, {
      $push: {
        products: created._id,
      },
    });

    return created;
  }

And everything works fine except this.userModel.findByIdAndUpdate is not updated if await is missing infront of it. Deal is there I do not care about the result from the update that's why I'm not using await I notice on some other services where await is missing infront of the db call, collection is updated correctly (again result db is not needed in the response that's why await is missing) so I'm wondering what is the behavior, how this works? Thanks a'lot!

1 Answers

From Mongoose documentation, queries are not promises.

Mongoose will not execute a query until then or exec has been called upon it (or writing await infront). This is very useful when building complex queries.

So to your question, you can try writing your code like this:

const created = document.save().exec();
Related