我有一个要显示的用户列表。我有2个过滤器
1)区域
2)分类
当我仅应用1个过滤器时,我会得到适当的过滤结果,即根据所选类别过滤用户或根据区域过滤用户。
现在我需要根据类别和区域选择过滤用户。 我应该如何获得所需的结果?
以下是根据所选类别过滤用户的工作代码:
User.find().populate('city').populate( {path: 'categories', match: { name: { $in: filterCatArray }}} ).populate('area').exec(function (err, users) {
users = users.filter(function(user) {
return user.categories; // return only filtered users
});
data = {fulldata:users};
res.render('home',{data:data});
});
用户架构:
var userSchema = new Schema({
city: {type: mongoose.Schema.Types.ObjectId, ref: 'City',required: true},
area: {type: mongoose.Schema.Types.ObjectId, ref: 'Area', required: true},
categories: [{type: mongoose.Schema.Types.ObjectId, ref: 'Category', required: true}],
status: { type: Boolean, default: true },
created_at: Date,
updated_at: Date
});
区域架构
var areaSchema = new Schema({
city: {type: mongoose.Schema.Types.ObjectId, ref: 'City'},
name: { type: String, required: true},
status: { type: Boolean, default: true },
created_at: Date,
updated_at: Date
});
类别架构
var catSchema = new Schema({
name: { type: String, required: true},
status: { type: Boolean, default: true },
created_at: Date,
updated_at: Date
});
城市架构
var citySchema = new Schema({
name: { type: String, required: true},
status: { type: Boolean, default: true },
created_at: Date,
updated_at: Date
});
答案 0 :(得分:1)
我是aggregation的新手,但我最近开始使用它。我认为populate
对于简单的情况很有用,但是当你想开始做复杂的事情,比如根据其他集合过滤结果时,你需要使用聚合。
这是未经测试但看起来大致如下:
UserSchema.aggregate([
// 1 join city collection
{
$lookup: {
from: 'citys',
localField: 'city',
foreignField: '_id',
as: 'city'
}
},
{
$unwind: '$city'
},
// 2 join area collection
{
$lookup: {
from: 'areas',
localField: 'area',
foreignField: '_id',
as: 'area'
}
},
{
$unwind: '$area'
},
// 3 join categories collection
{
$unwind: '$categories'
},
{
$lookup: {
from: 'categories',
localField: 'categories',
foreignField: '_id',
as: 'category'
}
},
// 4 filter results that only have specified categories
{
$match: {
'category.name': { $in: filterCatArray },
'area.name': 'something' // just an example
}
},
// 5 group results by user
{
$group: {
_id: '$_id',
city: { $first: '$city' },
area: { $first: '$area' },
categories: { $push: '$category' },
status: { $first: '$status' },
created_at: { $first: '$created_at' },
updated_at: { $first: '$updated_at' },
}
}
], function (err, users) {
});
如果出现问题,请从底部开始评论管道的每个阶段,看看发生了什么。
有关详细信息,请阅读以下链接: