node + express + mongodb搭建一个小网站时出现问题

Leezy__ 发布于 2016/02/22 17:10
阅读 992
收藏 0

我用的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);
    });
  }
});



其中Movie是mongoose的实例:

//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;



求大神帮忙

加载中
0
都哑
都哑

Cannotread property'save' of null

其实我不懂,我就看到了这一行,_movie是不是null

0
steambap
steambap

if (err){
        console.log(err);
}
node.js下的回调是这样的,如果出错,就直接callback(error),第二个参数就是undefined了。所以如果你的模块出错了,回调运行到上面代码这里只会在console中输出一下就继续运行了,所以有可能是你的不带_的Movie是undefined然后被underscore的extend成了Null。

返回顶部
顶部