1

I'm trying to query a Group document that has Users sub documents.

But I only want the subdocuments that belong to the user,

but I'm also getting data of other users.

Look at the query result, UserStatus field, only one of them belongs to the user.

The query result -

[
  {
    "_id": "5b1bcc12d5cdbf2cf78f2133",
    "name": "First group ever",
    "users": [
      {
        userId: 1,
        "userStatus": "I"
      },
      {
        userId: 2,
        "userStatus": "I"
      }
    ]
  }
]

Group.js -

const GroupSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    users: [{
        userId: {
            type: mongoose.SchemaTypes.ObjectId,
            ref: 'users',
            required: true
        },
        userStatus: {
            type: String,
            required: true
        }
    }]
})  

Query -

Group.find({
    "users": {
          $elemMatch: {
                userId: req.params.id, 
                $or: [{
                     userStatus: "I"
                }, {
                     userStatus: "A"
                }]
          }
        }
     }, "_id name users.userStatus",
     function (err, groups) {
        if (err)
            res.send(err)
        res.json(groups);
});
Ashh
  • 44,693
  • 14
  • 105
  • 132
Ore T
  • 29
  • 5

0 Answers0