I have a Program Schema which looks like this:
var ProgramSchema = new Schema({
active: { type: Boolean, default: false },
name: { type: String, required: true },
...
user: {
...
allowed: [{
type: Schema.Types.ObjectId,
ref: 'User'
}],
restricted: [{
type: Schema.Types.ObjectId,
ref: 'User'
}]
}
});
If allowed isn't empty and the User._id from logged User isn't in it, I don't want to show him the document.
If restricted isn't empty and the User._id from logged User is in it, I don't want to show him the document aswell.
My first idea was, that when I get all documents by Program.find(), I loop through each document and check if the document should be returned or not.
But isn't there a better solution than using forEach? Like using mongoose methods and filter documents before they get returned?
Solution
var query = {
'active': true, //shows only active programs
$or: [{ 'user.allowed': {$size: 0} }, { 'user.allowed': req.user._id }], //true if allowed is empty or has userId in it
'user.restricted': { $ne: req.user._id } //true if restricted doesn't contain userId
};
Program.find(query, 'name owner image categories user special', function (err, p) {
if(err) { return handleError(res, err); }
})
.sort({_id: -1})
.exec(function(err, programs){
if(err) { return handleError(res, err); }
res.json(200, programs);
});
Why not querying for your_user_id in the user.allowed array?
db.programs.find({'user.allowed': 'your_user_id'});