cubefox
cubefox

Reputation: 1301

mongoose extract nested arrays from multiple objects into one array

const userSchema = new Schema(
  {
    _id: Schema.Types.ObjectId,
    name: String,
    posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
    following: [{ type: Schema.Types.ObjectId, ref: "User" }]
  }
};

I want to extract all the posts from all the Users in the 'following' array, put them into one single array, sort them and then display the first 20. I was wondering if that is possible within the cursor or if I have to load it into memory.

function createFeed(user) {
  User.findOne({ name: user })
    .populate({
      path: "following",
      populate: {
        path: "posts"
      }
    })
//put all the posts into one array
.sort(...)  //sort by time created
.limit(...) //only get the newest n posts
.exec((err, result) => {
      if (err) console.log("error", err);
      console.log("result", //sorted tweets array);
 });
};

(I don't want to filter all the posts in my 'Posts' collection to check if they are made by the user since that would be a lot more expensive)

Upvotes: 1

Views: 209

Answers (2)

Daisy Antony Sancta
Daisy Antony Sancta

Reputation: 1

If you are trying to filter your populate with a condition, then you should be doing this:

User.findOne({ name: user })
.populate({
    path: 'posts',
    match: { user: 'XXX' }
})

Even more better would be to query the posts with the user filter condition and then populate user details.

Upvotes: 0

krbalaji
krbalaji

Reputation: 474

You can use distinct query in mongoDB

db.User.distinct('following',{})

Upvotes: 1

Related Questions