簡體   English   中英

如何在貓鼬中執行更新

[英]How to perform update in mongoose

我正在嘗試更新我的記錄,但是在我的情況下不會發生,並且我不確定該記錄出現問題的情況,有人可以建議我幫忙。謝謝

我的貓鼬代碼

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

};

我的圖式

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

我在郵遞員中的結果,{“ status”:“ success”,“ error_code”:0,“ result”:{“ ok”:0,“ n”:0,“ nModified”:0},“ message”:“文章更新成功” }

我正在嘗試更新我的記錄,但是在我的情況下不會發生,並且我不確定該記錄出現問題的情況,有人可以建議我幫忙。謝謝

確保在var id = req.params;中獲得您的id var id = req.params;

而且我敢肯定你不會像這樣得到你的id

檢查您的req.params; 值並在查詢中提供正確的ID

更新

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

您似乎忘記了指定密鑰。

更換

var id = req.params;

通過

var id = req.params.id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM