I'd like to have a single method that either creates or updates a document for a policy. Searching and trying different techniques like this one, I have come up with a null _id for my document. Using findByIdAndUpdate has a similar affect.
I see a document inserted in the collection, but the _id field is null:
exports.savePolicy = function (plcy, callback) { console.log('priority is : ' + plcy.priority) try { var policy = new Policy(plcy); var query = {_id: plcy._id}; //this may be null var update = { name: plcy.name || defaults.policyDefaults.name, longDescription: plcy.longDescription || defaults.policyDefaults.longDescription, shortDescription: plcy.shortDescription || defaults.policyDefaults.shortDescription, priority: plcy.priority, colorHex: plcy.colorHex || defaults.policyDefaults.colorHex, settings: plcy.settings || [], parentPolicyId: plcy.parentPolicyId || null } Policy.findOneAndUpdate(query, update, {upsert: true}, function (err, data) { callback(err, data); }); } catch (e) { log.error('Exception while trying to save policy: ' + e.message); callback(e, null); }
Is there something that can be done to get the _id not to be null when its not an update?
The below example shows that the findOneAndUpdate method will return the null value if we have not found any matching document in the collection.
findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document). I think that's the main difference. So the use case of updateOne is when you don't need the document and want to save a bit of time and bandwidth.
Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.
As the name implies, findOneAndUpdate() finds the first document that matches a given filter , applies an update , and returns the document. By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.
null
is a valid _id
value in MongoDB, so if you don't want it used in new docs you must ensure that a null
value is replaced with a new ObjectID
in query
:
var query = {_id: plcy._id}; if (!query._id) { query._id = new mongoose.mongo.ObjectID(); } // the rest stays the same...
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