gpt4 book ai didi

javascript - 如何编写 Mongoose 查询来组合来自两个模型的数据?

转载 作者:行者123 更新时间:2023-12-04 07:22:15 27 4
gpt4 key购买 nike

技术:MongoDB、ExpressJS
我有 3 个架构

  • 用户架构:
  • userSchema = {
    name: {type: String},
    password: {type: String},
    email: {type: String},
    friends: {type: [mongoose.Types.ObjectId]}
    }
  • textPostSchema =
  • textPostSchema = {
    text: {type: String},
    postType: {type: String, default: "textPost"},
    userId: {type: mongoose.Types.ObjectId}
    }
  • articalPostSchema:
  • articalPostSchema = {
    title: {type: String},
    content: {type: String}
    postType: {type: String, default: "articalPost"},
    userId: {type: mongoose.Types.ObjectId}
    }
    现在我有一个社交媒体应用程序,当用户的 friend 发布一个帖子时,我必须在其中显示这两个帖子,并且包括无限滚动。两者 textPostarticalPost应该发送到前端,并且一次只能发送总共 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',
    },
    },

    然后我创建了一个函数来只让 friend 发帖:
    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);
    }
    };

    最佳答案

    要使用 Mongoose 实现分页,您可以执行类似的操作。

    const getPosts = async (userId, pageNumber) => {
    let result = await Post.find({ userId })
    .skip((pageNumber - 1) * 10)
    .limit(10);

    return result;
    };
    pageNumber是一个您需要从前端传递的计数器,每当用户达到滚动限制时就会增加 1。
    如果要查询和合并来自多个集合的数据,则需要更新架构以使用 populate .只包括 ref您指的是其他集合的地方。
    这可能会有所帮助。
    https://mongoosejs.com/docs/populate.html

    关于javascript - 如何编写 Mongoose 查询来组合来自两个模型的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68419597/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com