mojo mojo - 29 days ago 7
Node.js Question

how to get all negative value document for particular user using express.js with mongodb?

i have all user data which is inserted in mongodb.

[
{

"user_id": "1",
"name": "aaaa",
"value": -10
}, {

"user_id": "2",
"name": "bbbb",
"value": 30

}, {
,
"user_id": "1",
"name": "aaaa",
"value": 310

}, {

"user_id": "2",
"name": "bbbb",
"value": -15
}, {

"user_id": "1",
"name": "aaaa",
"value": -100

}, {

"user_id": "3",
"name": "cccc",
"value": 390

}]


how to do query for my requirment?
in my document some user contaning value in negative .
for example user_id = 1 contaning two negative value object i need to find out using query how can i modify my code?

User.findOne({user_id: '1'},function(err, user) {
if (err) return next(err);
if (!user) return res.status(401).send('Unauthorized');
res.json(user);
});

Answer

To get multiple document use find instead of findOne. When you use find you get the output as array of objects. You can try the below code

User.find({user_id: '1' ,value : {$lt : 0}},function(err, users) { 
    if (err) return next(err);
    res.json(users);
});