SomethingOn
SomethingOn

Reputation: 10891

Can I query an array of subdocuments by multiple parameters with mongoose?

I'm trying to find a user by their social services using service type and account id, but I don't know how to do this as a Mongoose query.

For example, how would I find this user, using Mongoose, if I have 'twitter' and '789DEF'?

{
"email":"[email protected]",
"social": [
        {
            "service": "linkedin",
            "username": "Test User",
            "url": "https://www.linkedin.com/in/testuser",
            "accountId": "ABC12356"
        },
        {
            "service": "twitter",
            "username": "TestUser",
            "url": "https://www.twitter.com/testuser",
            "accountId": "789DEF"
        }
    ]
}

Upvotes: 0

Views: 417

Answers (1)

Jorge Aranda
Jorge Aranda

Reputation: 2080

You need the $elemMatch query operator. Assuming you have declared a mongoose model (let's say Users), then something like this should work:

Users.findOne({
    social: {
        $elemMatch: {
            service: 'twitter',
            accountId: '789DEF'
        }
    }
}, function (err, doc) {
    // doc contains your user document
});

If what you need is only the relevant social subdocument, then you should also use the $ projection operator:

Users.findOne({
    social: {
        $elemMatch: {
            service: 'twitter',
            accountId: '789DEF'
        }
    }
}).select('social.$').exec(function (err, doc) {
    // ...
});

Upvotes: 3

Related Questions