【问题标题】:How to get a paginated feed for a user which contains posts created by users whom he follows?如何为包含由他关注的用户创建的帖子的用户获取分页提要?
【发布时间】:2019-06-18 23:02:09
【问题描述】:

我正在为一个应用程序开发一个 nodejs 后端,在该应用程序中,用户将能够看到他/她关注的用户创建的帖子。

我想用猫鼬来做这个。

我的用户架构:

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    hashed_password: {
        type: String,
        required: true
    },
    isVerified: {
        type:Boolean,
        default: false
    },
    emailVerificationToken: String,
    emailVerificationTokenExpires: Date,
    followers: [{ type: ObjectId, ref: 'User'}],
    following: [{ type: ObjectId, ref: 'User'}],
    posts: [{type: ObjectId, ref: 'Post'}],
    bio: String,
    website: String
});

我的帖子架构:

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    url: {
        type: String,
        required: true
    },
    description: {
        type: String,
    },
    website: String,
    tags : [String],
    createdBy: { type: ObjectId, ref: 'User'}
});

我试过这个:

  User.findById(currentUserId)
    .populate("following","posts")
    .populate("following.posts","_id title")
    .skip()
    .limit()
    .exec(function(err,users){
      res.send(users);
    });

这是返回带有关注者和已填充帖子的分页用户。我只想要所有用户的帖子。谁能帮我解决这个问题?

【问题讨论】:

  • 如果您只是填充帖子 - .populate("posts") 会发生什么?

标签: node.js mongoose pagination


【解决方案1】:

我认为您在 userSchema 中将帖子拼错为 pin。

此外,您正在获取用户,相反,您应该获取包含该帖子的用户数据的所有帖子。

Post.find({})
    .populate("createdBy")
    .exec(function(err,users){
      res.send(users);
    });

【讨论】:

  • 我只想要当前登录用户关注的用户的帖子。有没有办法我可以添加一个过滤器来只过滤掉当前用户关注的那些用户?
  • Post.find({createdBy:userID})
  • 我仍然需要查询当前用户来获取他关注的用户。我想要的是获取由当前用户关注的用户创建的帖子列表(我可以稍后对其进行分页)。
  • this 是您可能正在寻找的内容
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多