node + express + mongodb搭建一个小网站时出现问题
我用的express为4.13.1,mongoose为4.4.4
在写一个学习的小网站时出现如下错误:
_movie.save(function(err, movie){ ^ TypeError: Cannot read property 'save' of null
//admin post movie router.post('/admin/movie/new', function(req, res){ var id = req.body.movie._id; var movieObj = req.body.movie; var _movie; if (id !== 'undefined'){ Movie.findById(id, function(err, movie){ if (err){ console.log(err); } _movie = _.extend(movie, movieObj); _movie.save(function(err, movie){ if (err){ console.log(err); } res.redirect('/movie/' + movie._id); }); }); }else { _movie = new Movie({ doctor: movieObj.doctor, title: movieObj.title, country: movieObj.country, language: movieObj.language, poster: movieObj.poster, year: movieObj.year, summary: movieObj.summary, flash: movieObj.flash }); _movie.save(function(err, movie){ if (err){ console.log(err); } res.redirect('/movie/' + movie._id); }); } });
//modules文件夹下movie.js var mongoose = require('mongoose'); var MovieSchema = require('../schemas/movie'); var Movie = mongoose.model('Movie', MovieSchema); module.exports = Movie; //schemas文件夹下movie.js var mongoose = require('mongoose'); var MovieSchema = new mongoose.Schema({ title: String, doctor: String, language: String, country: String, summary: String, flash: String, poster: String, year: Number, meta: { createAt: { type: Date, default: Date.now() }, updateAt: { type: Date, default: Date.now() } } }); MovieSchema.pre('save', function(next){ if (this.isNew){ this.meta.createAt = this.meta.updateAt = Date.now(); }else { this.meta.updateAt = Date.now(); } next(); }); MovieSchema.statics = { fetch: function(callback){ return this .find({}) .sort('meta.updateAt') .exec(callback) }, findById: function(id, callback){ return this .findOne({_id: id}) .exec(callback) } }; module.exports = MovieSchema;
求大神帮忙
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
node.js下的回调是这样的,如果出错,就直接callback(error),第二个参数就是undefined了。所以如果你的模块出错了,回调运行到上面代码这里只会在console中输出一下就继续运行了,所以有可能是你的不带_的Movie是undefined然后被underscore的extend成了Null。
Cannotread property'save' of null
其实我不懂,我就看到了这一行,_movie是不是null