user3766930
user3766930

Reputation: 5829

how can I parse an array of objects in my node.js and mongodb query?

In my webservice I was passing array of strings and then I was parsing it like this:

var users = req.body.users;

if (users) {
   var user = users.split(',');
   query.$and.push({"device_id": {$nin: user}});
}

but now my requirement changed and instead of strings I'm passing array like this:

"users": (
{
    "device_id" = "XXX";
    "display_name" = XXX;
    "facebook_username" = XXX;
    username = XXX;
},
{
    "device_id" = "YYY";
    "display_name" = YYY;
    "facebook_username" = YYY;
    username = YYY;
}
)

like before - I want to filter out all records that contain given device_ids. How can I modify my code so that it iterates over array (and take into consideration specific fields) instead of strings?

Upvotes: 0

Views: 64

Answers (1)

Bastiaanus
Bastiaanus

Reputation: 357

Assuming that req.body.users is an array try the following:

var users = req.body.users;
var excludedDeviceIds = [ ];

for(var i in users) {
    excludedDeviceIds.push(users[i]['device_id']);
}

query.$and.push({ 'device_id': { $nin: excludedDeviceIds } });

Edit:

If your environment supports ES6 you can also try:

query.$and.push({ 
    'device_id': { 
        $nin: users.map(user => user['device_id']) 
    } 
});

Upvotes: 1

Related Questions