猫鼬模式递归

nos*_*bor 3 mongoose node.js mongoose-schema

是否可以在猫鼬中进行递归?

例如,我想创建嵌套注释。

让我们考虑以下示例:

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] 
})
Run Code Online (Sandbox Code Playgroud)

在 SQL 中,使用键很容易实现这一点。

首先我想到的是在commentSchema 中添加字段,它将指向它正在回答的评论,但在这种情况下,如果评论只是数组中的一个简单对象,它们没有生成 id,所以这个解决方案在目前的设计中无法完成。

我想到的第二个解决方案是为评论创建一个单独的表,然后他们将拥有自己的 id,但这是在 mongodb 中进行的好方法吗?我的意思是它开始看起来与 SQL 表设计非常相似。

Tsv*_*nev 6

您可以使用该Schema.add()方法。首先定义没有递归属性的模式。将新创建的架构分配给commentSchema变量后,您可以通过调用该add()方法将其设置为属性类型。

const commentSchema = new mongoose.Schema({
  comment: String,
  author: String
});

commentSchema.add({ answers: [commentSchema] });
Run Code Online (Sandbox Code Playgroud)