0

I am developing a nodejs backend for an application in which a user will be able to see the posts created by the users he/she follows.

I want to do this using mongoose.

My userSchema:

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
});

My postSchema:

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'}
});

I have tried this:

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

This is returning paginated users with followers and their posts populated. I only want posts of all users. Can anyone please help me through this?

logdev
  • 292
  • 6
  • 22

1 Answers1

0

I think you have misspelled posts as pins in your userSchema.

Also you are getting users, instead you should get all posts with user data for that post.

Post.find({})
    .populate("createdBy")
    .exec(function(err,users){
      res.send(users);
    });
Vinil Prabhu
  • 1,279
  • 1
  • 10
  • 22
  • I only wants posts from users whom the current logged in user is following. Is there a way I can add a filter kind of a thing to filter out only those users whom the current user is following? – logdev Jun 19 '19 at 08:30
  • do `Post.find({createdBy:userID})` – Vinil Prabhu Jun 19 '19 at 10:03
  • I still need to query the current user to get the users whom he is following. What I want is to get a list of posts(which I can later paginate) which are createdBy users whom the current user is following. – logdev Jun 19 '19 at 11:05
  • [this](https://stackoverflow.com/q/27168022/5895297) is what you might be looking for – Vinil Prabhu Jun 20 '19 at 05:06