简体   繁体   中英

How to perform update in mongoose

I am trying to update my record,but its not happening in my case and i am not sure about the case where it went rong,can any one suggest me help.Thanks

My mongoose code,

exports.updatestudent = function (req, res) {
var student = new Student(req.body);
var data = {};
var id = req.params;
var params = req.body;
var item = {
    'name': params.name,
    'rollnumber': params.rollnumber,
    'class': params.class,
    'city': params.city
};
Student.update({ _id: id },{ $set: item }, function (err, result) {
    if (err) {
        console.log('err');
    }
    if (result) {
        data = { status: 'success', error_code: 0, result: result, message: 'Article updated successfully' };
        res.json(data);
    }
});

};

my schema,

  var StudentSchema = new Schema({
  name: {
    type: String
  },
  rollnumber: {
    type: String
  },
  class: {
    type: String
  },
   city: {
    type: String
  },
  status: {
    type: String
  },
  _id: {
    type: Schema.ObjectId
  }
});
/**
 * Hook a pre validate method to test the local password
 */
mongoose.model('student', StudentSchema, 'student');

my result in postman, { "status": "success", "error_code": 0, "result": { "ok": 0, "n": 0, "nModified": 0 }, "message": "Article updated successfully" }

I am trying to update my record,but its not happening in my case and i am not sure about the case where it went rong,can any one suggest me help.Thanks

Make sure that you are getting your id in var id = req.params;

And I am sure you will not get your id like this

check your req.params; values and give your correct id in the query

Update

var item = {};

if (params.name) {
  item.name = params.name;
}
if (params.rollnumber) {

  item.rollnumber = params.rollnumber
}


Student.update({
  _id: id
}, {
  $set: item
}, function(err, result) {
  if (err) {
    console.log('err');
  }
  if (result) {
    data = {
      status: 'success',
      error_code: 0,
      result: result,
      message: 'Article updated successfully'
    };
    res.json(data);
  }
});

It seems you forgot to specify the key.

Replace

var id = req.params;

By

var id = req.params.id;

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