TypeError: Cannot read property ‘_id’ of undefined 怎么解决
发布于 12 小时前 作者 EddieYD 46 次浏览 来自 问答

{ [CastError: Cast to ObjectId failed for value “” at path “_id”] message: ‘Cast to ObjectId failed for value “” at path “_id”’, name: ‘CastError’, kind: ‘ObjectId’, value: ‘’, path: ‘_id’, reason: undefined } { [ValidationError: Movie validation failed] message: ‘Movie validation failed’, name: ‘ValidationError’, errors: { _id: { [CastError: Cast to ObjectID failed for value “” at path “_id”] message: ‘Cast to ObjectID failed for value “” at path “_id”’, name: ‘CastError’, kind: ‘ObjectID’, value: ‘’, path: ‘_id’, reason: [Object] } } } d:\NodeWork\Study1\routes\index.js:105 res.redirect(’/movie/’ + movie._id) ^

TypeError: Cannot read property ‘_id’ of undefined at d:\NodeWork\Study1\routes\index.js:105:47 at d:\NodeWork\Study1\node_modules\mongoose\lib\document.js:1908:19 at handleError (d:\NodeWork\Study1\node_modules\mongoose\node_modules\hooks-fixed\hooks.js:40:22) at _next (d:\NodeWork\Study1\node_modules\mongoose\node_modules\hooks-fixed\hooks.js:46:22) at fnWrapper (d:\NodeWork\Study1\node_modules\mongoose\node_modules\hooks-fixed\hooks.js:186:18) at d:\NodeWork\Study1\node_modules\mongoose\lib\schema.js:200:17 at d:\NodeWork\Study1\node_modules\mongoose\node_modules\kareem\index.js:127:16 at nextTickCallbackWith0Args (node.js:420:9) at process._tickCallback (node.js:349:13)

Process finished with exit code 1

-----------------------这是源码

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, function (err, movie) { if (err) { console.log(err) }

    if (movie == undefined) {
        movie = new Movie({
            doctor: movieObj.doctor,
            title: movieObj.title,
            country: movieObj.country,
            language: movieObj.language,
            year: movieObj.year,
            poster: movieObj.poster,
            summary: movieObj.summary,
            flash: movieObj.flash
        })
    }

    _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, summary: movieObj.summary, flash: movieObj.flash });

_movie.save(function (err, movie) {
    if (err) {
        console.log(err)
    }
    res.redirect('/movie/' + movie._id)
})

} });

PS:有加过这个了 var bodyParser = require(“body-parser”);

var app = express();

app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));

回到顶部