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?
See Question&Answers more detail:os