【问题标题】:User, post, and comment model in mongoose猫鼬中的用户、帖子和评论模型
【发布时间】:2020-10-11 23:17:12
【问题描述】:

我正在制作一个与 Reddit 非常相似的论坛应用程序。我在这里使用猫鼬进行架构设计。我对我拥有的模型有一些疑问 - 用户、帖子和评论

  • 所有模型的架构看起来都正常吗?
  • 在用户中,我想在用户个人资料中显示朋友。就像你去他的个人资料时,会有类似Friends(200),当我点击时会出现朋友列表(如Facebook,然后点击你可以访问朋友的个人资料)。我还没有创建Friend 架构,但它真的需要吗?
  • 关于 cmets 的问题。到目前为止,我有基本的评论模式。线程化的 cmets 或回复会发生什么情况。如何存储它们?

我目前拥有的所有型号:

const userSchema = new Schema(
  {
    username: { type: String, required: true },
    email: { type: String, reuired: true },
    password: { type: String, required: true },
    country: { type: String, required: true },
    friends: [{ type: Schema.Types.ObjectId, ref: "Friend" }], // is it needed?
    posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
  },
  { timestamps: true }
)
const postSchema = new Schema(
  {
    title: { type: String, required: true },
    description: { type: String, required: true },
    user: { type: Schema.Types.ObjectId, ref: "User" },
    slug: { type: String, slug: "title" },
    upvotes: { type: Number },
    downvotes: { type: Number },
    city: { type: String }, // post will have a tag by the city like NewYork, LA etc.
  },
  { timestamps: true }
)
const commentSchema = new Schema(
  {
    comment: { type: String, required: true },
    post: { type: Schema.Types.ObjectId, ref: "Post"},
    user: { type: Schema.Types.ObjectId, ref: "User"},
    upvotes: { type: Number },
    downvotes: { type: Number }
  },
  { timestamps: true }
)

【问题讨论】:

    标签: javascript database mongodb mongoose mongoose-schema


    【解决方案1】:

    对于第二个问题,您不需要 friend 架构,因为 friend 也是 user

    【讨论】:

    • 那么,它应该在模式中还是不在?
    • 是的。你需要它。你可以像这样使用它。 friends: [{ type: Schema.Types.ObjectId, ref: "User" }], .
    • 那么,friendsUser 模型上,并且还引用了 User 模型?
    • friend 也是 user。因此,您将另一个 user 称为 friend
    【解决方案2】:

    对于第一个问题,为什么打算将用户的所有帖子存储在用户对象中作为list of posts,这意味着即使需要usernameemail 之类的基本内容,也要获取100 条帖子.相反,您可以将user_id 放在帖子架构中,帮助识别来自特定用户的帖子。

    【讨论】:

      猜你喜欢
      • 2022-09-30
      • 1970-01-01
      • 2014-08-19
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2020-07-06
      • 1970-01-01
      相关资源
      最近更新 更多