MongoError: Performing an update on the path '_id' would modify the immutable field '_id'解决办法

 问题

最近在用mongoose更新数据库时报了这个错误:

MongoError: Performing an update on the path '_id' would modify the immutable field '_id'

 我的代码:

// 建立数据集
var movie = new mongoose.Schema({
    movieName: String,
    movieImg: String,
    movieVideo: String,
    movieDownload: String,
    movieTime: String,
    movieNumSuppose: Number,
    movieNumDownload: Number,
    movieMainPage: Boolean
});

var movieModel = mongoose.model('movie', movie);
module.exports = movieModel;

// 错误的更新代码

var updateContent = new movie({
    movieName: req.body.movieName,
    movieImg: req.body.movieImg,
    movieVideo: req.body.movieVideo,
    movieDownload: req.body.movieDownload,
    movieTime: req.body.movieTime,
    movieNumSuppose: req.body.movieNumSuppose,
    movieNumDownload: req.body.movieNumDownload,
    movieMainPage: movieMainPage
});

movie.update({_id: req.body.movie_id}, updateContent, function (err, movieUpdate) {
    if(movieUpdate.nModified == 0 || err)
        res.json({status: 1, message: "电影信息没有改变或修改失败"+err});
    else
        res.json({status:0, message: "电影信息修改成功", data: movieUpdate});
})

 注:mongoose 的 update 语法 

Model.update(conditions, doc, [options], [callback])

conditions: 更新的条件,该值是一个对象。
doc: 需要更新的内容,该值也是一个对象。
options: 可选参数,它有如下属性:  safe,upsert,multi,runValidators,strict,overwrite
callback: 回调函数


解决办法

通过查阅资料终于发现了问题所在(红字部分): 这里的updateContent应该只是一个简单的对象,而不是一个Mongoose文档

// 正确的更新代码
var updateContent = {
    movieName: req.body.movieName,
    movieImg: req.body.movieImg,
    movieVideo: req.body.movieVideo,
    movieDownload: req.body.movieDownload,
    movieTime: req.body.movieTime,
    movieNumSuppose: req.body.movieNumSuppose,
    movieNumDownload: req.body.movieNumDownload,
    movieMainPage: movieMainPage
};

movie.update({_id: req.body.movie_id}, updateContent, function (err, movieUpdate) {
    if(movieUpdate.nModified == 0 || err)
        res.json({status: 1, message: "电影信息没有改变或修改失败"+err});
    else
        res.json({status:0, message: "电影信息修改成功", data: movieUpdate});
})

 

参考:Mongoose findOneAndUpdate() issue [duplicate]

你可能感兴趣的:(数据库)