我在 Mongoose 中有一个架构,它有一个自引用字段,如下所示:
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
的 _id
在哪里?我需要这个_id
。
最佳答案
在声明嵌入的 CollectPoint
项时,您应该构建一个新对象:
var data = new CollectPoint({
name: "Level 1",
collectPoints: [
new CollectPoint({
name: "Level 1.1",
collectPoints: []
})
]
});
这样,_id
和 collectPoints
将通过 CollectPoint
的实例化来创建,否则,您只是创建一个普通的 JSONObject。
为了避免此类问题,请构建 validator对于您的数组,如果其项目类型错误,则会触发错误:
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: []
}]
});
关于node.js - Mongoose 自引用架构不为所有子文档创建 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42475905/