0

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"
        }
    ]
}

1 Answer 1

3

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) {
    // ...
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.