简体   繁体   中英

Nodejs Mongoose Cannot update values in DB

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM