首页 > 解决方案 > MongoDB 基于参考 id 加入用户和点赞集合

问题描述

我正在尝试使用 ExpressJS 和 MongoDB 创建一个小型社交网络。我有一个关于喜欢和帖子收集的小问题。我知道您可以将 a 嵌入到likes集合posts中,但我决定将这两个集合分开并使用参考 ID,以便稍后加入它们。我目前遇到的主要问题是,如何在集合中包含likes参考?posts

假设我的posts架构看起来像这样:

const PostSchema = new Schema({
  content: { type: String, required: true },
  isLiked: false, 
}, { timestamps: true });

我的likes架构看起来像这样:

const LikeSchema = new Schema(
  {
    // The user who is liking the post.
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true
    },

    // The post that is being liked.
    question: {
      type: Schema.Types.ObjectId,
      ref: 'Question',
      required: true
    },
  },
  { timestamps: true }
);

我想这样做,以便每当我尝试查询帖子集合时,我也可以通过引用集合而不修改嵌入其中的模式来获得嵌入其中的喜欢likes

示例响应:

{
  _id: ObjectId("test"), 
  content: 'A post', 
  isLiked: false, 
  likes: ["A user object here based on the `likes collection`"]
}

标签: mongodbmongoose

解决方案


您必须在发送响应之前获取它们:

  1. 找到所有喜欢的帖子,类似于Like.find({ question: <postId> })
  2. 然后您可以解决喜欢的用户,在上面的命令中您可以.populate('user')猫鼬填充功能连接
  3. 如果您只对用户对象而不是整个类似对象感兴趣,则可以提取已解析的用户:const users = likes.map(x => x.user)
  4. 然后您可以将 users 数组添加到 post 对象并将最终对象作为响应发送

推荐阅读