首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何设计嵌套数据的模式

问如何设计嵌套数据的模式
EN

Stack Overflow用户
提问于 2020-11-15 12:47:05
回答 1查看 270关注 0票数 0

我创建了一个post Schema,实现注释和评论回复模式有困难,因为您无法预测一个评论回复有多少次有它自己的回复。

我用的是猫鼬和快车。

那么,如何实现这种模式设计呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-15 13:12:27

我认为您正在寻找这样的东西,您在这里引用注释模式中的注释。

在调用.find()时,我添加了一个中间件来预填充回复数组。您可以为其他调用(如.findOne()等)添加更多中间件。

代码语言:javascript
复制
const mongoose = require("mongoose");

const commentSchema = mongoose.Schema(
  {
    comment: {
      type: String,
      required: true
    },
    author: { // To reference the user that left the comment. If needed
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      ref: 'User',
    },
    replies:[{type: Schema.Types.ObjectId, ref: "Comment"}] // Array of comment replies
  },
  {
    timestamps: true,
  }
);

// Middleware to populate the replies when you call `find()`
commentSchema.pre('find', function() {
  this.populate('replies');
});

module.exports = mongoose.model('Comment', commentSchema);

您可以在这篇文章上做更深入的工作,这将向您展示如何在返回注释等时预先填充答复字段。

https://www.makeschool.com/academy/track/standalone/reddit-clone-in-node-js/comments-on-comments

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64844567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档