首页 > 解决方案 > 如何编写猫鼬查询来组合来自两个模型的数据?

问题描述

技术:MongoDB、ExpressJS

我有 3 个架构

  1. 用户架构:
userSchema = {
  name: {type: String},
  password: {type: String},
  email: {type: String},
  friends: {type: [mongoose.Types.ObjectId]}
}
  1. textPostSchema =
textPostSchema = {
   text: {type: String},
   postType: {type: String, default: "textPost"},
   userId: {type: mongoose.Types.ObjectId}
}
  1. articalPostSchema:
articalPostSchema = {
  title: {type: String},
  content: {type: String}
  postType: {type: String, default: "articalPost"},
  userId: {type: mongoose.Types.ObjectId}
}

现在我有一个社交媒体应用程序,当用户的朋友帖子是帖子时,我必须在其中显示这两个帖子,并包括无限滚动。如果要发送到前端,则两者都textPost应该articalPost发送,并且一次只能发送 10 个帖子。我应该如何为时间线编写 API?

输出应如下所示:

{
  post: [
          {
           title: "artical Post title", 
           content: "artical post content", 
           postType: "articalPost", 
           userId: "60b9c9801a2a2547de643ccd"
          },
          {
           text: "text post ", 
           postType: "textPost", 
           userId: "60b9c9801a2a2547de643ccd"
          }, 
          ... 8 more
        ]
}

更新: 我得到了解决方案:-我在更多架构上创建:

timelineSchema = {
    postId: {
      type: mongoose.Types.ObjectId,
      required: true,
      ref: function () {
        switch (this.postCategoryType) {
          case 'articleposts':
            return 'ArticlePost';
          case 'textposts':
            return 'TextPost';
        }
      },
    },
    postCategoryType: {
      type: String,
      required: true,
    },
    userId: {
      type: mongoose.Types.ObjectId,
      required: true,
      ref: 'User',
    },
  },

然后我创建了一个函数来只让朋友发帖:

exports.getTimelinePosts = async (req, res) => {
  try {
    const timelinePosts = await TimelineModel.find({
      userId: { $in: [...req.user.friends, req.params.id] },
    })
      .skip((req.params.page - 1) * 10)
      .limit(10)
      .sort({ createdAt: -1 })
      .populate('postId');
    return res.status(200).json({ status: 'success', data: timelinePosts });
  } catch (error) {
    return res.status(500).json(error);
  }
};

标签: javascriptmongodbexpressmongoosemongodb-query

解决方案


假设您使用的是 express 和 mongoose。获取两者的代码,

// first bring all those schema from your mongoose models
const Article = require('./models/ArticleSchema');
const Text = require('./models/TextSchema');

const fetchArticleAndTextPost = async (req, res)=>{
    //find all data 
    const articles = await Article.find();
    const texts = await Text.find();

    //join them together
    const post = articles.concat(texts);

    return res.status(200).json({
        status: 200,
        data: post,
    })

}


推荐阅读