In order to create a document if it doesn't already exist, you need to pass { upsert : true } in the options hash as it defaults to false . i.e. update is deprecated. Use updateOne, updateMany, or bulkWrite instead.
If findOneAndUpdate doesn't find any document that matches your request, doesn't mean that it's an error. err is null because there is no error in the execution of the request. It's true that your code is asynchronous, but you're using callbacks, so the given err and doc is exactly what it should be returned.
Upsert with update() method: If a document or documents found that matches the given query criteria, then the update() method updates the document/documents. If no document/documents match the given query criteria, then the update() method inserts a new document in the collection.
Model. updateMany = function ({}, {cid: ''}, function(err) { ... }); I believe that Mongoose wraps your cid in a $set, so this is not the same as running that same update in the mongo shell. If you ran that in the shell then all documents would be replaced by one with a single cid: '' .
You are looking for the new
option parameter. The new
option returns the newly created document(if a new document is created). Use it like this:
var query = {},
update = { expire: new Date() },
options = { upsert: true, new: true, setDefaultsOnInsert: true };
// Find the document
Model.findOneAndUpdate(query, update, options, function(error, result) {
if (error) return;
// do something with the document
});
Since upsert
creates a document if not finds a document, you don't need to create another one manually.
Since you wish to refactor parts of your code to be shorter and simpler,
async / await
.findOneAndUpdate()
as suggested in this answer
let query = { /* query */ };
let update = {expire: new Date()};
let options = {upsert: true, new: true, setDefaultsOnInsert: true};
let model = await Model.findOneAndUpdate(query, update, options);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With