为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用猫鼬嵌套模式?

如何使用猫鼬嵌套模式?

www说 2022-12-22 14:41:14
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。我以前见过这个,所以我不知道它是否可能
查看完整描述

2 回答

?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

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


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);

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


查看完整回答
反对 回复 2022-12-22
?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

在您的顶部代码段中,您有responses: [CommentSchema]但 CommentSchema 仍未定义,因为此代码段正在定义它。您不能进行这种递归定义。



查看完整回答
反对 回复 2022-12-22
  • 2 回答
  • 0 关注
  • 154 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号