findOneAndUpdate does not work if no callback provided
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.
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:
- Passing a callback to it
- Use it like a promise (use 'then' or await the function)
- 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.
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.