0

I have a Community Schema:

var community = mongoose.Schema({
    subject: String,
    body: String,   
    members: [{
        isModerator: { type: Boolean, default: false },
        muted: { type: Boolean, default: false }, 
        deactivated: { type: Boolean, default: false }, 
        status: String, // waiting (only in default community), active, invited, blocked, muted
        date: Date,
        profile: { type: mongoose.Schema.Types.ObjectId, ref: 'profile' }
    }]
});

I Want to get Only 1 member from the array of members in a community as i know profile id of that member in a community. But When I am trying to get it return whole Community details including all members. The way i tried is:

db.getCollection('communities').find({"_id":bjectId("593fe3cc32f9e76c7752fbbc"), "members.profile": {$eq: ObjectId("5949fa79948f3e18e0dea3bb")}})

Or by using Code:

    var query={};
    query.id = req.query.batchId;
    query['members.profile'] = {
        $eq: req.query.profileId
    };
    db.community.findOne(query)
        .populate('members.profile')
        .exec(function(err, member){
            if(err){
                return res.failure(err);
            }
             return res.success();
         });

I understand as i am trying to get(find) community that is why it return whole community. But my Question is how can i get only 1 member from Array of Members in a community while getting community? Any Help would be appreciated.

Ankit Manchanda
  • 562
  • 6
  • 21
  • I think you should have two separate table. One for community and one for members where members can be identified by the unique community ID or something like that. – error404 Jul 14 '17 at 08:57
  • Specifically the answer telling you to use the [positional `$` operator](https://docs.mongodb.com/manual/reference/operator/projection/positional/) to project only the matched element. `.find({ "_id": ObjectId("593fe3cc32f9e76c7752fbbc"), "members.profile": {$eq: ObjectId("5949fa79948f3e18e0dea3bb") }).select({ "members.$": 1 })` which uses `.select()` for projection with mongoose. Or `.project()` with the native driver. – Neil Lunn Jul 14 '17 at 09:33
  • $elemMatch and $match is not working with objectId – Ankit Manchanda Jul 17 '17 at 11:22

0 Answers0