Tuesday, 14 March 2017

Mongoose Update *ONE* Field if Found Otherwise Create Replacement

Suppose I have a schema with multiple fields. I want to update only ONE field if a document matches my query. However, if not, I want to create a new document with values for all fields. Is there a way to use Model.findOneAndUpdate for this?

Here is code for more concreteness and what I have tried:

var mg = require('mongoose');   
var Record = mg.model ("record", {
  field1: Number,
  field2: Number,
  field3: Number,
});

//Update field1 ONLY if found using findOneAndUpdate, else create with all fields
var query = {//My Query},
    update = {field1: 10}
    options = {upsert: true, new: true, setDefaultsOnInsert: true};

Record.findOneAndUpdate(query, update, options, function(err,result){
  //Do stuff with doc
});

The above code updates field1 correctly, but when no document matches the query, a new document is created without field2 or field3



via Alex H

No comments:

Post a Comment