[英]Apply filter if value exists otherwise ignore - mongoose
I have the following field within my collection: 我的收藏夹中包含以下字段:
"intent" : [
"Find a job",
"Advertise a job"
],
What I'm trying to do is basically filter results on that field. 我想做的基本上是在该字段上过滤结果。
So if the end user passes in 因此,如果最终用户通过
[
"Find a job",
]
I would then return all documents that have the intent Find a job
this is my query so far: 然后我会回到有意向的所有文件Find a job
,这是我的查询到目前为止:
var _intent = req.body.intent;
Reason.find({ intent: { $in: _intent }}, function (err, reason) {
if (err) {
res.send(err);
}
res.json(reason);
});
Now this works when I specify a value for intent
as I'm using the $in
- Logical Query Operator however when I do not specify a value for intent
it fails to return any documents, so what I'm asking is, is there a way I can say if intent
has a value then filter on it, otherwise if it doesn't then do not apply the filter? 现在,当我使用$in
in-逻辑查询运算符为intent
指定值时,此方法有效,但是当我不为intent
指定值时,它无法返回任何文档,所以我要问的是我可以说如果intent
有一个值,然后对其进行过滤,否则,如果不这样做,则不应用该过滤器?
Why not set the query object dynamically? 为什么不动态设置查询对象?
var query = {};
if ( req.body.hasOwnProperty('intent') )
query.intent = { "$in": req.body.intent };
Reason.find(query, function(err, reason) {
});
Or even 甚至
if ( req.body.intent.length > 0 )
Which ever case of logic suits. 哪种逻辑都适合。 It's all just JavaScript after-all. 毕竟都是JavaScript。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.