I have looked at other posts and none seem to address what I'm trying to do. I need to create a query that searches for all records that have type_ids in an array, AND belong to the current logged in user. Here is what I have:
Query:
app.post('/photos', function(req, res) {
Photos
.find({
'type_id': { $in: req.body.type_ids },
$and : {'groups.users': { $in: req.user._id }}
})
.select('name size')
.exec(function(err, data) {
return res.json(data);
});
});
Schema:
var photoSchema = mongoose.Schema({
name : String,
size : String,
type_id : String,
created : {
type: Date,
default: Date.now
},
groups : {
users : [],
other : []
}
});
The only thing I can get to work is the following query:
app.post('/photos', function(req, res) {
Photos
.find({'type_id': { $in: req.body.type_ids }})
.select('name size')
.exec(function(err, data) {
return res.json(data);
});
});
But, obviously this won't work because I only want those results for a particular user. The line $and : {'groups.users': { $in: req.user._id }}
clearly isn't working, but I'm not sure how to fix it. Any ideas?
The "and" operator is implied in queries, so $and
is rarely necessary. You can just use:
{
'type_id': { $in: req.body.type_ids },
'groups.users': { $in: req.user._id }
}
Although, based on the name of the variable, the second line sounds wrong - you probably want just 'groups.users': req.user._id
(you should drop the $in
).
Finally, the way to use $and
is by giving it an array:
{
'$and': [
{ 'type_id': { $in: req.body.type_ids } },
{ 'groups.users': { $in: req.user._id } }
]
}
But like I said, its unnecessary here.