I've got a web api written using expressjs and mongoosejs.
The main schema in the app contains a subdocument, permissions, which contains array fields. Those arrays contain ids of users who can perform an action on that document.
I'm trying to limit results of a query on that collection by the values in the read subdocument array field:
Here's the main schema:
var MainSchema = new Schema({
uri: { type: String, required: false },
user: { type: String, required: false },
groups: [String],
tags: [String],
permissions: {
read: [String],
update: [String],
delete: [String]
}
});
I want to return documents that have a specific value in the permissions.read array or where that array is empty.
My code doesn't throw an error, but doesn't limit the results; I still get documents that don't match the given value, and aren't empty.
Here's what I've got:
var MainModel = mongoose.model('MainSchema', MainSchema);
app.get('/api/search', function (req, res) {
var query = MainModel.find({'uri': req.query.uri });
// This works fine
if (req.query.groups) {
query.where('groups').in(req.query.groups);
}
else if (req.query.user) {
query.where('user').equals(req.query.user);
}
// How can I return only documents that match req.query.user or ""?
query.where('permissions.read').in([req.query.user, ""]);
query.exec(function (err, results) {
if (!err) {
return res.send(results);
} else {
return console.log(err);
}
});
});
I have a hunch that the where clause is not testing the value of each of the elements of permissions.read against each of the values of the array passed to the in clause.
Thanks.
EDIT: Here's a document that shouldn't be returned, but is (note, permissions.read array includes a value that's not the current user's ID):
{
"user": "[email protected]",
"uri": "http://localhost:3000/documents/test",
"permissions": {
"delete": [
"[email protected]"
],
"update": [
"[email protected]"
],
"read": [
"[email protected]"
]
},
"tags": [],
"groups": [
"demo",
"2013"
]
}
EDITED: Corrected Model/Schema confusion, which wasn't in my code, but was left out in the copy/paste. Thanks.
permissions: []) or an array containing an empty string (permissions: [''])? Can you edit your question to include an example doc that's being returned that shouldn't?MainSchemato reference the model instead of the schema? Other than that it all looks fine and unfortunately I'm not able to reproduce the problem with that doc. It's omitted from the results unless I setreq.query.user = "[email protected]".