Mongoose错误findByIdAndUpdate在强制转换中失败

时间:2014-07-21 14:20:24

标签: node.js mongodb mongoose

尝试使用findByIdAndUpdate更新文档,我收到一个我不理解的错误。

    console.log(req.body);
    var data = req.body;
    data._id = undefined;
    Package.findByIdAndUpdate(req.params.id, data, function (err, pkg) {
        if (err) {
            console.log(err.stack);
            return next(restify.InternalServerError(err));
        }
        res.json(pkg);
        next();
    });

我收到以下错误:

TypeError: Cannot read property '_id' of undefined
at ObjectId.cast (/home/ubuntu/workspace/server/node_modules/mongoose/lib/schema/objectid.js:109:12)
at ObjectId.castForQuery (/home/ubuntu/workspace/server/node_modules/mongoose/lib/schema/objectid.js:165:17)
at Query._castUpdateVal (/home/ubuntu/workspace/server/node_modules/mongoose/lib/query.js:2009:17)
at Query._walkUpdatePath (/home/ubuntu/workspace/server/node_modules/mongoose/lib/query.js:1969:25)
at Query._castUpdate (/home/ubuntu/workspace/server/node_modules/mongoose/lib/query.js:1865:23)
at castDoc (/home/ubuntu/workspace/server/node_modules/mongoose/lib/query.js:2032:18)
at Query._findAndModify (/home/ubuntu/workspace/server/node_modules/mongoose/lib/query.js:1509:17)
at Query.findOneAndUpdate (/home/ubuntu/workspace/server/node_modules/mongoose/node_modules/mquery/lib/mquery.js:2056:15)
at Function.Model.findOneAndUpdate (/home/ubuntu/workspace/server/node_modules/mongoose/lib/model.js:1250:13)
at Function.Model.findByIdAndUpdate (/home/ubuntu/workspace/server/node_modules/mongoose/lib/model.js:1344:32)

我已经验证了id有效,数据也是一个有效的对象。

我的模特:

mongoose.model('Package', {
    name: {
        required: true,
        type: String
    },
    servers: [mongoose.Schema.Types.ObjectId],
    packageType: {
        type: String,
        enum: ['package', 'subscription']
    },
    subscriptionPeriodInDays: Number,
    pointsIncluded: Number,
    price: Number,
    rank: String,

    data: mongoose.Schema.Types.Mixed //For custom solutions
});

日志还会打印有效的data对象

{
    name: 'Your Package',
    packageType: 'subscription',
    subscriptionPeriodInDays: 30,
    pointsIncluded: 10000,
    price: 10,
    rank: 'Donator',
    _id: undefined,
    __v: 0,
    servers: [],
    description: '<p>test</p>\n'
}

我曾尝试使用调试器,但我无法找到原因。

2 个答案:

答案 0 :(得分:2)

正如Rale​​igh所说,你需要删除_id字段。您可以delete data._id;而不是data._id = undefined;来完成。

答案 1 :(得分:0)

我相信Mongoose正试图将_id的值设置为undefined,因为_id值仍然通过数据对象传入。

尝试在更新模型之前删除行data._id = undefined;或从数据对象中完全删除_id字段。