【发布时间】:2020-07-20 23:34:10
【问题描述】:
我有一个模型:
const comment = new mongoose.Schema({
id: { type: ObjectId, required: true },
comment: { type: String },
replies: [comment]
});
想要创建这样的文档:
{
"id": 1,
"comment": "Grand Parent Comment",
"replies": [
{
"id": 11,
"comment": "Parent Comment",
"replies": [
{
"id": 111,
"comment": "Comment",
"replies": [
{
"id": 1111,
"comment": "Child Comment",
"replies": []
}
]
},
{
"id": 112,
"comment": "Sibling Comment",
"replies": []
}
]
}
]
}
根据这个answer的回答
只需使用
this作为模型的参考即可解决。
const comment = new mongoose.Schema({
id: { type: ObjectId, required: true },
comment: { type: String },
- replies: [comment]
+ replies: [this]
});
当我尝试使用 Typescript 时,会出现如下错误:
'this' 隐含类型为 'any',因为它没有类型注释。
在 typescript 上使用猫鼬书写建模自我引用的任何最佳实践。
【问题讨论】:
-
我看到的区别是你用 const 声明而示例答案用 var 声明,也许?
-
sorry我觉得没什么区别,因为当我尝试用“var”或“const”声明时,还是会出现同样的错误。
标签: typescript mongoose mongoose-schema