4

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!

Andon Mitev
  • 1,354
  • 1
  • 11
  • 30
  • Did you check the MongoDB to see if it's updated or not? – Gabriel Lupu Dec 13 '20 at 13:32
  • the first argument to findByIdAndUpdate function is supposed to be the Id correct? does data.user variable contain the Id? – BEvo Dec 13 '20 at 13:32
  • Even if you don't care about `result` you should care about that the update operation is completed successfully. Otherwise you could miss an exception if this update operation fails for some reason. – Anatoly Dec 13 '20 at 13:47
  • @GabrielLupu yes mongodb was not updated, i was thinking my $push is not working right – Andon Mitev Dec 13 '20 at 13:54
  • @Bevo yes this is the user id it's fine with await infront of it db is updated – Andon Mitev Dec 13 '20 at 13:55
  • @Anatoly yes you are right, but let's say i don't care if the operation is success or fail – Andon Mitev Dec 13 '20 at 13:55
  • @AndonMitev ok, you can pass a callback as the third param and add `console.log` there to see if your update has finished with either a result or an error – Anatoly Dec 13 '20 at 14:01
  • 1
    If you remove `await` then you might have an `UncaughtPromiseRejection` error in the future. If you don't want to wait for the function then just put a trailing catch method (`findByIdAndUpdate(...).catch((ex) => console.trace(ex));`) – Mehmet Baker Dec 13 '20 at 14:59
  • @AndonMitev check my answer & let me know if it works for you – domenikk Dec 13 '20 at 15:28
  • If you don't care about the result from the update, you [should not just omit the `await`](https://stackoverflow.com/q/32384449/1048572). (Also, while you may not care about the result, you still seem to care about the update itself, so you *should* `await` it anyway). – Bergi Dec 13 '20 at 17:07

1 Answers1

3

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();
domenikk
  • 1,723
  • 1
  • 10
  • 12