无法使用mongoose

时间:2016-04-14 19:45:49

标签: node.js mongodb mongoose

我有一个简单的模型,即:

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var citySchema   = new Schema({
    name: { type: String, required: true },
    state: { type: Schema.Types.ObjectId, ref: 'State' }
});

module.exports = mongoose.model('City', citySchema);

只有我访问一条路线,要求插入一个城市,作为邮政参数

POST:{   名称:'我的城市',   州:'SE'//代表一些国家 }

我知道state属性的类型不正确,但在我的逻辑中我做了:

var newCity = new City(req.body);

if (typeof req.body.state !== 'undefined' && req.body.state.length == 2) {
    State.findOne({uf: req.body.state.toUpperCase()}, function(err, foundState) {
        if (err) { res.send({status: 500, message: 'Could not find the required state'}); return; }
        newCity.state = foundState._id;
        newCity.set('state', foundState._id);
        return;
    });
}

但是,一旦我执行res.send(newCity),检查newCity变量属性,它会打印:

{
  "name": "Balneário Camború",
  "_id": "570ff2944c6bd6df4e8e76e8"
}

如果我尝试保存它,我会收到以下错误:

ValidationError: CastError: Cast to ObjectID failed for value \"SE\" at path \"state\""

所以,我很困惑,因为当使用req.body属性创建Model时,它不会列出state属性,即使我稍后在代码中设置它,但是当我尝试保存City时,它会输入错误的错误。

导致这种情况的原因,我应该如何处理?

0 个答案:

没有答案