Reputation: 1219
I'am developing some application on MEAN.js boilerplate and I've got one problem which I'm not able to solve by myself :( I've got a following database scheme:
var UserSchema = new Schema({
profession: {
type: Schema.ObjectId,
ref: 'Profession'
},
game: {
type: Schema.ObjectId,
ref: 'Game'
}
};
var ProfessionSchema = new Schema({
assignedTaskCategories: [{
type: Schema.ObjectId,
ref: 'TaskCategory'
}]
});
var TaskCategorySchema = new Schema({
professions: [{
type: Schema.ObjectId,
ref: 'Profession'
}],
assignedToGame: {
type: Schema.ObjectId,
ref: 'Game'
}
});
var TaskSchema = new Schema({
game: {
type: Schema.ObjectId,
ref: 'Game'
},
inCategories: [{
type: Schema.ObjectId,
ref: 'TaskCategory'
}]
});
Now I would like to get all Tasks, which have got some element in inCategories
same as User's profession taskCategories array.
I've tried this, but it returns nothing
Profession.find({ _id: req.user.profession }).exec(function(err, userCategories) {
if(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
Task.find({ game: req.user.game, inCategories: userCategories.assignedTaskCategories}).exec(function(err, tasks) {
if(err) {
return res.status(400).sed({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(tasks);
}
});
}
});
Could anyone help me with this? :) If my approach is bad, please tell me the right way how can I solve it :)
We cannot use $setEquals, because the array are not same, consider following example:
Profession programmer is able to solve following task categories: Programming, Presentation, Wash dishes
Profession secretary is able to solve following task categories: Presentation, Wash dishes
Then we will create a task, which is assigned to category: Wash dishes, so the professions assignedCategories
arrays are bigger, not equal to task's inCategories
array.
Upvotes: 0
Views: 85
Reputation: 103305
Try using the aggregation framework where you employ the $setEquals
operator to compare the arrays. In the following pipeline, the operator determines if the Tasks' inCategories
array and the assignedTaskCategories
array contain the same elements:
Profession.find({ _id: req.user.profession }).exec(function(err, userCategories) {
if(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
var pipeline = [
{
"$match": { "game": req.user.game }
},
{
"$project": {
"game": 1,
"inCategories": 1,
"sameElements": {
"$setEquals": [ "$inCategories", userCategories[0].assignedTaskCategories ]
}
}
},
{
"$match": { "sameElements": true }
}
];
Task.aggregate(pipeline)
.exec(function (err, tasks){
if(err) {
return res.status(400).sed({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(tasks);
}
});
}
});
Upvotes: 1