javascript - MongoDB/Mongoose: Updating entire document with findOneAndUpdate() -


i want use findoneandupdate() method either create document if doesn't exist, or update if exist. consider following code:

       samplecomment = new comment({             id: '00000001',             name: 'my sample comment',             ...         }) 

this attempt find out if samplecomment aldready exists, , if so, update it, otherwise creating it:

        comment.findoneandupdate(             { id: samplecomment.id },              { samplecomment }, // <- not passing object             { upsert: true, setdefaultsoninsert: true },              function(error, result) {                 ...         }); 

i'm trying pass model-instance object in second argument, result returning default values of model. same goes document itself.

how pass entire object samplecomment correctly in second argument?

by default returned result going unaltered document. if want new, updated document returned have pass additional argument named new value true.

comment.findoneandupdate({id: samplecomment.id}, samplecomment, {new: true, upsert: true, setdefaultsoninsert: true}, function(error, result) {     if(error){         console.log("something wrong when updating data!");     }      console.log(result); }); 

see http://mongoosejs.com/docs/api.html#query_query-findoneandupdate:

function(error, doc) {   // error: errors occurred   // doc: document before updates applied if `new: false`, or after updates if `new = true` } 

Comments

Popular posts from this blog

ios - Is 'init' forbidden as *part* of a variable name? -

javascript - Why Selenium can't find an element that is graphically visible -

angular - Angular2 Router: Cannot find primary outlet to load 'HomeComponent' -