为什么我的Mongoose模式缺less其中的一个字段?

这是我的模式:

var RegionSchema = new Schema({ "metadata": { "type": String, "name": String, "children": [{ "name": String, "type": String }], "parent": Schema.ObjectId }, "data": [DataContainer] }); 

这是我正在写的一个unit testing,在这个testing中,我用一些空值存储了这个对象的一个​​实例:

 describe('Region with no data', function() { it('Should save without error', function(done) { var emptyRegion = new Region({ "metadata": { "type": "City", "name": "San Diego", "children": [], "parent": null }, "data": [] }); emptyRegion.save(function(err, saved) { console.log(saved) if (err) throw err; if (saved.metadata.name === "San Diego") done(); }) }); }); 

但是,当我尝试打印出保存的内容时,我得到以下结果:

 { __v: 0, _id: 551cd261cc55c5ff48c8150b, data: [] } 

为什么我的metadata对象没有保存? 即使在save调用之前, emptyRegion看起来就像那样。 我没有正确定义我的metadata吗?

烦人的罪魁祸首是元数据子文档中的type字段。 Mongoose解释这意味着元数据是Stringtypes,并有一堆不相关的属性。 将您的模式定义更改为以下,它应该工作:

 var RegionSchema = new Schema({ "metadata": { "type": {"type": String}, "name": String, "children": [{ "name": String, "type": {"type": String} }], "parent": Schema.ObjectId }, "data": [DataContainer] }); 

或者,为您的type字段使用不同的名称。