Ima*_*oko 6 mongoose typescript mongoose-schema
我有一个模型:
const comment = new mongoose.Schema({
id: { type: ObjectId, required: true },
comment: { type: String },
replies: [comment]
});
Run Code Online (Sandbox Code Playgroud)
想要创建这样的文档:
{
"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": []
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
根据这个答案的回答
this只需作为模型的参考即可解决。
{
"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": []
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用 Typescript 时,会出现如下错误:
“this”隐式具有“any”类型,因为它没有类型注释。
使用猫鼬在打字稿上书写进行自我引用建模的任何最佳实践。
小智 4
您可以尝试使用以下方法分两步执行此操作add:
const schema = new mongoose.Schema({
body: String,
});
schema.add({
children: [schema]
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1184 次 |
| 最近记录: |