根据登录用户的偏好,我想在视图中创建一个集合并显示。
我对mongodb没有任何经验,现在我以这个巨大的if / else语句结束,而且它已经很慢(数据库中有7个用户)。但afaik它确实给了我正确的结果。
Meteor.publish('listprofiles', function () {
if ( ! this.userId ) return [];
var user = Meteor.users.findOne({ _id: this.userId }, {
fields : {
'profile.gender': 1,
'profile.preference': 1
}
}),
query;
user.gender = user.profile.gender;
user.preference = user.profile.preference;
if (user.gender === 'man') {
if (user.preference === 'straight') {
query = {
$and: [
{ 'profile.gender': 'woman' },
{
$or : [{ 'profile.preference' : 'straight' },
{ 'profile.preference' : 'bi' }]
}
]
};
} else if (user.preference === 'gay') {
query = {
$and: [
{ 'profile.gender': 'man' },
{
$or : [{ 'profile.preference' : 'gay' },
{ 'profile.preference' : 'bi' }]
},
]
};
} else if (user.preference === 'bi') {
query = {
$or: [
{
$and: [
{ 'profile.gender': 'man' },
{
$or : [{ 'profile.preference' : 'gay' },
{ 'profile.preference' : 'bi' }]
},
]
},
{
$and: [
{ 'profile.gender': 'woman' },
{
$or : [{ 'profile.preference' : 'straight' },
{ 'profile.preference' : 'bi' }]
}
]
}
]
};
}
查询有效,我对它们进行了测试,但我不确定如何动态调整它们。我的猜测是查询也不应该是一个对象,但我不确定如何创建一个有效的变量..
var dbFindQuery = Meteor.users.find({
'profile.invisible': false,
queryShouldBeHereButObviouslyThisDoesNotWork
}, {
fields : {
'profile.name': 1,
'profile.city': 1,
'profile.country': 1,
'profile.gender': 1,
'profile.preference': 1,
'profile.story': 1
}
});
console.log(dbFindQuery.fetch());
return dbFindQuery;
任何人都可以给我指向正确的方向吗?
答案 0 :(得分:1)
你当然可以分解出常见的查询对象。这是接近它的一种方法:
Meteor.publish('listprofiles', function() {
if (!this.userId)
return [];
var user = Meteor.users.findOne(this.userId);
var gender = user.profile.gender;
var preference = user.profile.preference;
var straightOrBiWoman = {
'profile.gender': 'woman',
'profile.preference': {$in: ['straight', 'bi']}
};
var gayOrBiMan = {
'profile.gender': 'man',
'profile.preference': {$in: ['gay', 'bi']}
};
var query = {};
if (gender === 'man') {
switch (preference) {
case 'straight':
query = straightOrBiWoman;
break;
case 'gay':
query = gayOrBiMan;
break;
default:
query = {$or: [gayOrBiMan, straightOrBiWoman]};
}
}
query['profile.invisible'] = false;
return Meteor.users.find(query, {fields: {profile: 1}});
});
我们根据用户的straightOrBiWoman
和gayOrBiMan
重复使用gender
和preference
。请注意,我使用$in operator来简化查询。我还建议您不要在fields
修饰符中指定第二级字段,原因如here所述。最后,我建议测试这段代码,因为在重写代码时我可能错过了逻辑中的一些东西。希望这个例子能够帮助您指导正确的方向。