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

1
  • 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? Commented Nov 18, 2015 at 11:14

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.