Reputation: 1355
Working on an API I want to do a full document update of a MongoDB object.
This is my current code that works but it feels wrong to have to delete the _id every time. Is there a better way to do this?
PutDoco : function(doco){
return new Promise(function(Resolve,Reject){
delete doco._id;
db.collection('docos').updateOne(
{"details.ID":doco.details.ID},
doco,
function(err,result){
if(err)
return Reject(err);
Resolve(result);
}
);
});
},
Upvotes: 0
Views: 797
Reputation: 312085
You can use replaceOne
instead when replacing all contents of a document (besides _id
which is immutable). And because replaceOne
returns a promise if you don't pass it a callback, you can reduce your whole function down to:
return db.collection('docos').replaceOne({"details.ID":doco.details.ID}, doco);
However, it might be clearer (and faster) to find the document to replace using _id
instead:
return db.collection('docos').replaceOne({_id: doco._id}, doco);
Upvotes: 2