Bertus Kruger
Bertus Kruger

Reputation: 1355

How to replace a document matched by _id?

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

Answers (1)

JohnnyHK
JohnnyHK

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

Related Questions