是否可以在 Mongoose 中进行递归?
例如,我想创建嵌套注释。
让我们考虑以下示例:
commentSchema = new mongoose.Schema({
comment : String,
author : String,
answers : [commentSchema] // ReferenceError: commentSchema is not defined
})
productSchema = new mongoose.Schema({
name : {type: String, required: true},
price : Number,
comments : [commentSchema]
})
在 SQL 中,使用键很容易实现这一点。
我首先想到的是在 commentSchema 中添加 parent 字段,该字段将指向它正在回答的评论,但在这种情况下,如果评论是只是数组中的简单对象,它们没有生成 id,因此在当前设计中无法完成此解决方案。
我想到的第二个解决方案是为评论创建一个单独的表,然后它们将有自己的 id,但是这是在 mongodb 中执行 go 的好方法吗? 我的意思是它开始看起来与 SQL 表设计非常相似。
最佳答案
您可以使用Schema.add()
方法。首先,定义不带递归属性的架构。将新创建的架构分配给 commentSchema
变量后,您可以通过调用 add()
方法将其设置为属性类型。
const commentSchema = new mongoose.Schema({
comment: String,
author: String
});
commentSchema.add({ answers: [commentSchema] });
关于node.js - Mongoose 模式递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48050606/