Node.js Mongoose自引用架构不为所有子文档创建ObjectId
我在mongoose中有一个模式,它有一个自引用字段,如下所示:Node.js Mongoose自引用架构不为所有子文档创建ObjectId,node.js,mongodb,mongoose,mongoose-schema,Node.js,Mongodb,Mongoose,Mongoose Schema,我在mongoose中有一个模式,它有一个自引用字段,如下所示: var mongoose = require('mongoose'); var CollectPointSchema = new mongoose.Schema({ name: {type: String}, collectPoints: [ this ] }); 插入CollectPoint对象时: { "name": "Level 1" } 没关系,结果和预期的一样: { "_id": "58b36c83
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"
}]
}
其中是子集合点模式的
\u id
?我需要此\u id
在声明嵌入的收集点
项时,您应该构建一个新对象:
var data = new CollectPoint({
name: "Level 1",
collectPoints: [
new CollectPoint({
name: "Level 1.1",
collectPoints: []
})
]
});
这样,通过实例化CollectPoint
将创建\u id
和collectPoints
,否则,您只需创建一个普通的JSONObject
为避免此类问题,请为数组构建一个,如果其项的类型错误,则会触发错误:
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'
}
}
});
谢谢,伙计,你的回答澄清了猫鼬中我没有注意到的基本概念。但我觉得奇怪的是,当我添加
collectPoints:[this]
时,它应该强制new..()
,或者这个关系应该在模型中。。(对不起,我只是在这里分道扬镳)我用计算机解决了这个问题。
var data = new CollectPoint({
name: "Level 1",
collectPoints: [{
name: "Level 1.1",
collectPoints: []
}]
});