[英]Query MongoDb for multiple fields with $regex
我正在关注Angular Meteor教程,它具有以下代码:
import { Meteor } from 'meteor/meteor';
import { Counts } from 'meteor/tmeasday:publish-counts';
import { Parties } from './collection';
if (Meteor.isServer) {
Meteor.publish('parties', function(options, searchString) {
const selector = {
$or: [{
// the public parties
$and: [{
public: true
}, {
public: {
$exists: true
}
}]
}, {
// when logged in user is the owner
$and: [{
owner: this.userId
}, {
owner: {
$exists: true
}
}]
}]
};
if (typeof searchString === 'string' && searchString.length) {
selector.name = {
$regex: `.*${searchString}.*`,
$options : 'i'
};
}
Counts.publish(this, 'numberOfParties', Parties.find(selector), {
noReady: true
});
return Parties.find(selector, options);
});
}
我正在尝试修改selector.name以包括描述字段。 我已经检查了添加选择器。描述,但是什么也没做。 是否可以将选择器修改为包括多个字段的搜索,同时使正则表达式与文档的任一字段匹配?
通过“任一个”,您可能意味着$or:
-如果仅向对象添加description
,则最终将得到$and:
在获得名称和描述标准之前,选择器将是:
let selector =
{ $or:
[
{ $and: [ { public: true }, { public: { $exists: true } } ] },
{ $and: [ { owner: this.userId }, { owner: { $exists: true } }] }
]
};
(注意let
而不是const
)
为此,您需要$and:
附加第二个$or:
if (typeof searchString === 'string' && searchString.length) {
selector = { $and:
[
selector,
{ $or:
[
{ name: { $regex: `.*${searchString}.*`, $options : 'i' }},
{ description: { $regex: `.*${searchString}.*`, $options : 'i' }},
]
}
]
};
}
最后,您应该具有一个类似于以下内容的对象:
{ $and:
[
{ $or: [ public criteria, owner criteria ] },
{ $or: [ name regex, description regex ] }
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.