0

I want to retrieve a single object from a nested array of an object in mongoose. I have attached sample json code below.

{
        "_id" : ObjectId("1"),
        "name" : "xxx",
        "votes" : [
                {
                        "actionType" : 11,
                        "voter" : [
                                {
                                        "user" : "john",
                                        "pass" : a 
                                },
                                {
                                        "user" : "david",
                                        "pass" : b
                                }
                        ]
                },
                {
                        "actionType" : 22,
                        "voter" : [
                                {
                                        "user" : "john",
                                        "pass" : c 
                                },
                                {
                                        "user" : "david",
                                        "pass" : d
                                }
                        ]
                }
        ]
}

Expected result as

{
   "user":"john",
   "pass":c
} 

Explanation: I want user object where actionType=22 and user=john

0

1 Answer 1

1
`var obj = {};
var votes = response.votes;
votes = response.votes[];
for(var i=0; i<votes.length; i++) {
    if(votes[i].actionTypes === 22) {
        var voter = votes[i].voter;
        for(var i = 0; i<voter.length;i++) {
                if(voter[i].name === 'john') {
                    obj.push(voter[i]);
                    break;
                } 
        }
    }
}

`
Sign up to request clarification or add additional context in comments.

1 Comment

Thank for your answer. But i want this in mongoose query.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.