Mongoose自引用模式不为所有子文档创buildObjectId

我有一个在mongoose中有一个自引用字段的Schema,像这样:

var mongoose = require('mongoose'); var CollectPointSchema = new mongoose.Schema({ name: {type: String}, collectPoints: [ this ] }); 

当插入一个CollectPoint对象时:

 { "name": "Level 1" } 

没关系,结果如预期:

 { "_id": "58b36c83b7134680367b2547", "name": "Level 1", "collectPoints": [] } 

但是当我插入自引用的子文档时,

 { "name": "Level 1", "collectPoints": [{ "name": "Level 1.1" }] } 

它给了我这个:

 { "_id": "58b36c83b7134680367b2547", "name": "Level 1", "collectPoints": [{ "name": "Level 1.1" }] } 

孩子CollectPointSchema_idCollectPointSchema ? 我需要这个_id

声明embedded的CollectPoint项目时,应该创build一个新的对象:

 var data = new CollectPoint({ name: "Level 1", collectPoints: [ new CollectPoint({ name: "Level 1.1", collectPoints: [] }) ] }); 

这样, _idcollectPoints将由collectPoints的实例创build,否则,您只是创build一个普通的JSONObject。

为了避免这些问题,为您的数组构build一个validation器 ,如果它的项目types错误,将触发错误:

 var CollectPointSchema = new mongoose.Schema({ name: { type: String }, collectPoints: { type: [this], validate: { validator: function(v) { if (!Array.isArray(v)) return false for (var i = 0; i < v.length; i++) { if (!(v[i] instanceof CollectPoint)) { return false; } } return true; }, message: 'bad collect point format' } } }); 

这样下面会触发一个错误:

 var data = new CollectPoint({ name: "Level 1", collectPoints: [{ name: "Level 1.1", collectPoints: [] }] });