为了账号安全,请及时绑定邮箱和手机立即绑定

跪求大神帮忙解决TypeError: Cannot read property 'save' of undefined

折腾了一个晚上,还是搞不定,body-parser已经安装了。mongodb也安装好了,提交数据就出错。其他功能正常。

(node:10084) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html

{ CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model "Movie"

    at MongooseError.CastError (E:\webapp\imooc\node_modules\mongoose\lib\error\cast.js:26:11)

    at ObjectId.cast (E:\webapp\imooc\node_modules\mongoose\lib\schema\objectid.js:147:13)

    at ObjectId.castForQuery (E:\webapp\imooc\node_modules\mongoose\lib\schema\objectid.js:187:15)

    at cast (E:\webapp\imooc\node_modules\mongoose\lib\cast.js:229:32)

    at Query.cast (E:\webapp\imooc\node_modules\mongoose\lib\query.js:2752:12)

    at Query.findOne (E:\webapp\imooc\node_modules\mongoose\lib\query.js:1353:10)

    at E:\webapp\imooc\node_modules\mongoose\lib\query.js:2310:21

    at new Promise.ES6 (E:\webapp\imooc\node_modules\mongoose\lib\promise.js:45:3)

    at Query.exec (E:\webapp\imooc\node_modules\mongoose\lib\query.js:2304:17)

    at Function.findById (E:\webapp\imooc\schemas\movie.js:43:5)

    at E:\webapp\imooc\app.js:75:9

    at Layer.handle [as handle_request] (E:\webapp\imooc\node_modules\express\lib\router\layer.js:95:5)

    at next (E:\webapp\imooc\node_modules\express\lib\router\route.js:131:13)

    at Route.dispatch (E:\webapp\imooc\node_modules\express\lib\router\route.js:112:3)

    at Layer.handle [as handle_request] (E:\webapp\imooc\node_modules\express\lib\router\layer.js:95:5)

    at E:\webapp\imooc\node_modules\express\lib\router\index.js:277:22

  message: 'Cast to ObjectId failed for value "undefined" at path "_id" for model "Movie"',

  name: 'CastError',

  stringValue: '"undefined"',

  kind: 'ObjectId',

  value: 'undefined',

  path: '_id',

  reason: undefined,

  model:

   { [Function: model]

     hooks: Kareem { _pres: {}, _posts: {} },

     base:

      Mongoose {

        connections: [Object],

        plugins: [],

        models: [Object],

        modelSchemas: [Object],

        options: [Object] },

     modelName: 'Movie',

     model: [Function: model],

     db:

      NativeConnection {

        base: [Object],

        collections: [Object],

        models: [Object],

        config: [Object],

        replica: false,






TypeError: Cannot read property 'save' of undefined

    at Movie.findById (E:\webapp\imooc\app.js:81:10)

    at E:\webapp\imooc\node_modules\mongoose\lib\query.js:2326:9

    at newTickHandler (E:\webapp\imooc\node_modules\mpromise\lib\promise.js:234:18)

    at _combinedTickCallback (internal/process/next_tick.js:67:7)

    at process._tickCallback (internal/process/next_tick.js:98:9)


正在回答

8 回答

原因在这里

if (id !== 'undefined') {
        Movie.findById(id, function (err, movie) {
            if (err) {
                console.log(err);
            } else {
                _movie = underscore.extend(movie, movieObj);
            }
        });
    }

这里的ID是从表单中读取的 没有输入的话 是字符串的'undefined' 并非js中未赋值的变量值的关键字`undefined`。

是从http://cnodejs.org/topic/552a3a7ecd5ee87201ab1edc 得到的启示 要求ID为Objectid,是因为id不符合导致的错误,检查代码发现undefined 未加引号。

表单数据在提交时 如下所示:

movie[_id]:undefined
move[title]:佛挡杀佛大是大非
move[doctor]:456645
move[country]:456645
move[year]:456645
move[poster]:456645
move[summary]:456645
move[flash]:456645
move[language]:456645


1 回复 有任何疑惑可以回复我~
#1

依韵_宵音

写代码需要细心,不过犯错很多的原因还是对这些东西不熟悉 熟悉了就不会犯这样的错误了,或者说很容易排查这样的错误。
2017-01-17 回复 有任何疑惑可以回复我~

这个想要弄得清楚,最好学一下后台语言,如php了解表单数据是怎么提交给服务器端的。就能完全明白。

0 回复 有任何疑惑可以回复我~

if (id !== 'undefined' && id !== '')

应该要这样

0 回复 有任何疑惑可以回复我~

TypeError: Cannot read property 'save' of undefined
    at E:\stq\stq\app.js:65:11
    at E:\stq\stq\node_modules\mongoose\lib\query.js:2745:9
    at tryCatcher (E:\stq\stq\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (E:\stq\stq\node_modules\bluebird\js\release
\promise.js:512:31)
    at Promise._settlePromise (E:\stq\stq\node_modules\bluebird\js\release\promise.js
:569:18)
    at Promise._settlePromise0 (E:\stq\stq\node_modules\bluebird\js\release\promise.j
s:614:10)
    at Promise._settlePromises (E:\stq\stq\node_modules\bluebird\js\release\promise.j
s:689:18)
    at Async._drainQueue (E:\stq\stq\node_modules\bluebird\js\release\async.js:133:16
)
    at Async._drainQueues (E:\stq\stq\node_modules\bluebird\js\release\async.js:143:1
0)
    at Immediate.Async.drainQueues (E:\stq\stq\node_modules\bluebird\js\release\async
.js:17:14)
    at runCallback (timers.js:651:20)
    at tryOnImmediate (timers.js:624:5)
    at processImmediate [as _immediateCallback] (timers.js:596:5)

0 回复 有任何疑惑可以回复我~

为啥我有单引号也不行

0 回复 有任何疑惑可以回复我~

同求 相同的问题

0 回复 有任何疑惑可以回复我~
#1

青了葱的老王

看楼上。。
2017-01-28 回复 有任何疑惑可以回复我~
// admin post movie
app.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, (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,
            year:movieObj.year,
            poster:movieObj.poster,
            flash:movieObj.flash,
            summary:movieObj.summary
        });
 
        _movie.save(function(err, movie) {
            if (err) {
                console.log(err);
            };
 
            res.redirect('/movie/' + movie._id);
        });
    }
});

问题出在这段代码里,找了半天,一句一句跟人家对,还是找不出毛病。。。恳请各位大哥大姐帮我看看问题在哪。。。

0 回复 有任何疑惑可以回复我~
#1

青了葱的老王

ar movieObj = req.body.movie; var _movie; if (id !== undefined) { undefined 加上单引号 =》 if (id !== 'undefined') 应该就好了!
2017-01-28 回复 有任何疑惑可以回复我~

这是app.js 源码

"use strict";


var express = require('express');
var path = require('path')
var mongoose = require('mongoose');
var _ = require('underscore');
var Movie = require('./models/movie');
var port = process.env.PORT || 3000;
var app = express();
var bodyParser = require('body-parser');


mongoose.connect('mongodb://127.0.0.1:27017/imooc');
mongoose.connection.on('connected', function () {
  console.log('Connection success!');
});

app.set('views', './views/pages');
app.set('view engine', 'jade');
app.use(bodyParser.urlencoded({ extende: true}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,'./bower_components')));
app.use(express.static(path.join(__dirname,'./static')));
app.listen(port);

console.log('Imooc started on port ' + port);


app.get('/',(req,res)=>{
	Movie.fetch(function(err, movies) {
		if (err) {
			console.log(err);
		}
  res.render('index',{
      title:'MOMO 首页',
      movies:movies
  	})
  })
});

app.get('/movie/:id',(req,res)=>{
	var id = req.params.id;
	Movie.findById(id, (err,movie)=>{
	  res.render('detail',{
      title:'Imooc' + movie.title,
      movie: movie
  	});
	});
});

app.get('/admin/movie',(req,res)=>{
  res.render('admin',{
      title:'MOMO 后台',
      movie:{
        doctor:'',
        country:'',
        title:'',
        year:'',
        poster:'',
        language:'',
        flash:'',
        summary:'',
      }
  })
});

// admin post movie
app.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, (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,
			year:movieObj.year,
			poster:movieObj.poster,
			flash:movieObj.flash,
			summary:movieObj.summary
		});

		_movie.save(function(err, movie) {
			if (err) {
				console.log(err);
			};

			res.redirect('/movie/' + movie._id);
		});
	}
});
// admin list
app.get('/admin/list',(req,res)=>{
	Movie.fetch(function(err, movies) {
		if (err) {
			console.log(err);
		}
  res.render('list',{
      title:'Imooc 电影列表页',
      movies: movies
  	})
	});
});

// admin update movie
app.get('/admin/update/:id',(req, res)=>{
	var id = req.params.id;

	if (id) {
		Movie.findById(id,(err,movie)=>{
			res.render('admin',{
				title: 'Imooc 后台更新页',
				movie: movie
			});
		});
	}
});


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
node+mongodb 建站攻略(一期)
  • 参与学习       91860    人
  • 解答问题       889    个

带你完整实现一个从前端到后端的项目,初中级前端开发工程师必学课程

进入课程

跪求大神帮忙解决TypeError: Cannot read property 'save' of undefined

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信