如何使用猫鼬嵌套模式?

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 不存在的引用错误。如何使用 mongoose 嵌套模式?我认为错误是因为在 const commentschema 中调用了 commentSchema。我以前见过这个,所以我不知道它是否可能


www说
浏览 155回答 2
2回答

吃鸡游戏

您是否尝试在创建架构后添加“响应”字段?const CommentSchema = new mongoose.Schema({    username: {        type: String,        required: true,    },    detail: {        type: String,        required: true,    },});CommentSchema.add({ responses: [CommentSchema] });不过,我可能会这样做的方式是保留您的原始设置并将响应保存为评论模型的 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);然后只需根据需要填充“响应”字段。

至尊宝的传说

在您的顶部代码段中,您有responses: [CommentSchema]但 CommentSchema 仍未定义,因为此代码段正在定义它。您不能进行这种递归定义。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript