如何使用猫鼬嵌套架构?

时间:2020-08-07 04:13:20

标签: javascript mongoose

const CommentSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
    },

    detail: {
        type: String,
        required: true,
    },
    responses: [CommentSchema]

})



const PostSchema = new mongoose.Schema({
    author: {
        type: String,
        required: true,
    },
    title: {
        type: String,
        required: true
    },
    comments: [CommentSchema]


})

我不断收到评论错误,指出CommentSchema不存在。如何将模式与猫鼬嵌套在一起?我认为错误是因为在const commentschema内部调用了commentSchema。我以前看过这件事,所以我不知道是否可能

2 个答案:

答案 0 :(得分:0)

在最上面的代码段中,您有responses: [CommentSchema],但由于该代码段是在定义CommentSchema,因此Comment尚未定义。您无法进行这种递归定义。

答案 1 :(得分:0)

创建架构后,您是否尝试过添加“响应”字段?

const CommentSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
    },

    detail: {
        type: String,
        required: true,
    },
});
CommentSchema.add({ responses: [CommentSchema] });

尽管如此,我可能会做的是保留原始设置并将响应保存为Comment模型的ObjectId。

const CommentSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
    },

    detail: {
        type: String,
        required: true,
    },
    responses: [{ type: ObjectId, ref: 'Comment' }],
});

const Comment = model('Comment', CommentSchema);

然后只需根据需要填充“响应”字段即可。