**app.post(’/admin/movie/new’,function(req,res){ var id = req.body.movie._id; var movieObj = req.body.movie; var _movie; console.log(id); if(id !== ‘undefined’){ //用于更新数据 Movie.findById({_id:id},function(err,movie){ if(err){ console.log(err); return; }else{ movie.title = req.body.title; movie.doctor = req.body.doctor; movie.country = req.body.country; movie.language = req.body.language; movie.poster = req.body.poster; movie.flash = req.body.flash; movie.year = req.body.year; movie.summary = req.body.summary; movie.save(function(err,movie){ if(err){ console.log(‘something is wrong’); } res.redirect(’/movie/’+movie._id); }); }
})
}else{
//用于新增数据
_movie = new Movie({
title:movieObj.title,
doctor:movieObj.doctor,
country:movieObj.country,
language:movieObj.language,
poster:movieObj.poster,
summary:movieObj.summary,
flash:movieObj.flash,
year:movieObj.year
});
_movie.save(function(err,movie){
if(err){
console.log(err);
return err;
}
res.redirect('/movie/'+movie._id);
});
}
});** 这段代码我想用于更新数据和插入数据。插入数据时没有问题,更新时就报错,错误如下 { [CastError: Cast to ObjectId failed for value “undefined” at path “_id”] stack: ‘Error\n at MongooseError.CastError (/home/harwin/node/imovie/node_modules/mongoose/lib/error/cast.js:18:16)\n at ObjectId.cast (/home/harwin/node/imovie/node_modules/mongoose/lib/schema/objectid.js:134:13)\n at ObjectId.castForQuery (/home/harwin/node/imovie/node_modules/mongoose/lib/schema/objectid.js:187:17)\n at module.exports (/home/harwin/node/imovie/node_modules/mongoose/lib/cast.js:201:32)\n at Query.cast (/home/harwin/node/imovie/node_modules/mongoose/lib/query.js:2491:10)\n at Query.findOne (/home/harwin/node/imovie/node_modules/mongoose/lib/query.js:1236:10)\n at /home/harwin/node/imovie/node_modules/mongoose/lib/query.js:2113:21\n at new Promise.ES6 (/home/harwin/node/imovie/node_modules/mongoose/lib/promise.js:45:3)\n at Query.exec (/home/harwin/node/imovie/node_modules/mongoose/lib/query.js:2106:10)\n at Function.MovieSchema.statics.findById (/home/harwin/node/imovie/schemas/movie.js:44:14)\n at exports.detail (/home/harwin/node/imovie/routes/user.js:8:11)\n at callbacks (/home/harwin/node/imovie/node_modules/express/lib/router/index.js:164:37)\n at param (/home/harwin/node/imovie/node_modules/express/lib/router/index.js:138:11)\n at param (/home/harwin/node/imovie/node_modules/express/lib/router/index.js:135:11)\n at pass (/home/harwin/node/imovie/node_modules/express/lib/router/index.js:145:5)\n at Router._dispatch (/home/harwin/node/imovie/node_modules/express/lib/router/index.js:173:5)’, message: ‘Cast to ObjectId failed for value “undefined” at path “_id”’, name: ‘CastError’, kind: ‘ObjectId’, value: ‘undefined’, path: ‘_id’, reason: undefined }