Mongoose不会使用数组创建模型对象

时间:2016-03-07 07:54:39

标签: node.js mongoose

我正在开发一个项目,我有以下mongoose模式:

module.exports = mongoose.model('Env', {
    name : {type : String, default: ''},
    services: [ServiceAddress]
});

module.exports = mongoose.model('ServiceAddress', {
    serviceId : {type : ObjectId},
    address: {type: String}
});

我正在尝试更新现有的“Env”文档,该文档包含一系列“服务”。

router.put('/api/env', function(req, res, next) {
    var env = new Environment(req.body);
    env.save(function(err, updated){
        if (err){
            res.send(err);
        }
        res.json(updated);
    });
});

req.body内容是:

{
   _id: "56dd26a6618c1b983d5bada6", 
   name: "Test Drive"
   services: [{_id: "56dc6e385fb0b038241d3399", address: "11"}, {_id:     "56dc6e595fb0b038241d339a", address: ""}]
}

但是DB中的结果是(只推送了ID):

"services" : [ { "_id" : ObjectId("56dc6e385fb0b038241d3399") }, { "_id" : ObjectId("56dc6e595fb0b038241d339a") }

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

请尝试使用以下代码段

var serviceSchema = {
    serviceId : {type : ObjectId,required: false},
    address: {type: String,required: false}
};
// added so that new _id field is not added when object is pushed in array
serviceSchema  = 'new Schema('+serviceSchema +',{_id:false})';

module.exports = mongoose.model('Env', {
    name : {type : String, default: ''},
    services: [serviceSchema], default:[],
});

由于