mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

findOneAndUpdate does not work if no callback provided

Open ahmadx87 opened this issue 7 years ago • 2 comments

I'm using mongoose 5.3.12. The situation is simple I'm trying to find and update a document (and create it if it doesn't exist) findOneAndUpdate({ ... }, { ... }, { upsert: true })

I do not need a callback for it, I just want to save it and the rest of my code does not depend on it. But the issue is if I provide no callback or do not use 'then' this command fails with no warnings or errors. If I provide an empty callback it works fine.

ahmadx87 avatar Sep 14 '19 21:09 ahmadx87

You can refer the documentation of mongoose https://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

The function you are using just return a query. It will be executed in 3 ways:

  1. Passing a callback to it
  2. Use it like a promise (use 'then' or await the function)
  3. Use '.exec()' following the function.

The 2 and 3 method will make your code synchronous, so if you dont want that function blocks your program and you are not going to use the return document, maybe the 1 method suits you.

VietNguyenQuoc avatar Sep 17 '19 16:09 VietNguyenQuoc

You should just do findOneAndUpdate({ ... }, { ... }, { upsert: true }).exec() with no callback. Mongoose doesn't automatically execute queries, you need to either call exec() or then(), or await on it.

vkarpov15 avatar Sep 23 '19 20:09 vkarpov15