0

I am pretty new to Nodejs and MongoDB. This might be a simple error, but I cannot seem to update values from DB. I searched far and wide but my syntax is seem to be right. Please help me.

var dataConstruct = {}
dataConstruct[fieldName] = fieldValue;
updateRecordModel.find(dataConstruct , function(err, field) {
  if(err) {
    logger.error("Error deleting records. Error -" + err)
    callback(err, "Error while searching for record.Please cheack the values posted")
  }
  else {
    logger.info("JSON"+JSON.stringify(field[0].Option1));
    field[0].Option1="Max";
    logger.info("JSON"+JSON.stringify(field[0].Option1));
    if(field){
       //code to update
  }
  else{
    callback(err, "No such data present")
  }
  }

}).lean();

Find is returning data . I am using .lean() to get javascript object instead of document model object so that I can modify data. I cannot seem to modify the data returned without using .lean() as is the problem in this post Why can't you modify the data returned by a Mongoose Query (ex: findById)

I tried to find the data and update or resave it, I tried all the update syntax and methods(including find and then save doc again) mentioned in this post https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications but none seem to work,as I cannot modify the data returned

This is the json returned from find {"_id":"564c29d96bf38ba3039f4844","Option1":"Gary","Option2":"Fred","__v":0}

I need to know how to update this value

This is the code I used for findoneand update

    updateRecordModel.findOneAndUpdate({"Option1": "Gary" }, { "Option1": "Max" }, function(err,records) {
    if (err) throw err;
    console.log(records);
    });

In console record is being returned without being updated

Community
  • 1
  • 1
ShinyJos
  • 1,487
  • 11
  • 17
  • What query are you running when you try to update? What issues are you running into when you try it? This would be a clear use of the `findOneAndUpdate`. When you tried using the `findOneAndUpdate` as you described, what did you use on the params? – João Antunes Nov 18 '15 at 11:14

2 Answers2

1

You can try after field[0].Option1="Max"; use save method. field[0].save() . I hope it help

Helen
  • 176
  • 10
1

Since mongoose 4.0 the returned value by the findOneAndUpdate is always the old document. If you want the new one to be returned (the updated document) you have to pass {new: true} in the options, as stated in their documentation.

You should end up with something like this:

updateRecordModel.findOneAndUpdate({"Option1": "Gary" }, { "Option1": "Max" }, {new: true}, function(err,records) {
  if (err) throw err;
  console.log(records);
});
João Antunes
  • 521
  • 4
  • 9