简体   繁体   English

如何在猫鼬中执行更新

[英]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" } 我在邮递员中的结果,{“ status”:“ success”,“ error_code”:0,“ result”:{“ ok”:0,“ n”:0,“ nModified”:0},“ message”:“文章更新成功” }

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; 确保在var id = req.params;中获得您的id var id = req.params;

And I am sure you will not get your id like this 而且我敢肯定你不会像这样得到你的id

check your req.params; 检查您的req.params; values and give your correct id in the query 值并在查询中提供正确的ID

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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