Home > Back-end >  Getting all documents based on attributes of referenced document in MongoDB
Getting all documents based on attributes of referenced document in MongoDB

Time:10-08

I have a family model

FamilySchema = new mongoose.Schema({
    name: { type: String, required: true },
    users: [
      {
          user: { type: mongoose.Schema.Types.ObjectId,ref: 'user', required: true },
      },
    ],
    admin: { type: mongoose.Schema.Types.ObjectId, ref: 'user', required: true },});

I have a user model

UserSchema = new mongoose.Schema({
    name: { type: String, required: true },
    family: { type: mongoose.Schema.Types.ObjectId, ref: 'family', required: true },});

I have a post model

PostSchema = new mongoose.Schema({
   user: { type: mongoose.Schema.Types.ObjectId, ref: 'user', required: true },});
});

I want to get posts of all users of the same family.

I am currently doing this by first getting all the users from the family and then querying the posts.

const users = await User.find({ family: req.user.family }).select('id');

const userPosts = await Post.find({ user: { $in: users } })

Is there a way that mongo handles this for me in a single query?

CodePudding user response:

Try MongoDB aggregation

Ex :

db.users.aggregate([
  {
    "$match": {
      "family": req.user.family
    }
  },
  {
    "$lookup": {
      "from": "posts",
      "localField": "_id",
      "foreignField": "user",
      "as": "posts"
    }
  }
])

https://mongoplayground.net/p/4qG4PJx8lDV

  • Related