简体   繁体   English

如果值存在则应用过滤器,否则忽略-猫鼬

[英]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.

相关问题 检查 mongoose sava() data 如果不存在则创建文档,否则更新数据 - checked mongoose sava() data Create document if not exists, otherwise, update data 检查文档是否已经存在,如果是,则进行更新,否则创建新的-猫鼬 - Check if document already exists and if yes then update, otherwise create new - Mongoose 如果文档存在,则 Firestore 增量值,否则设置它 - Firestore increment value if document exists, otherwise set it 如何检查猫鼬中是否存在值 - How to check if a value exists in mongoose 如果key存在则从object取值否则取值 - Take value from object if key exists otherwise take value Mongoose findOneAndUpdate 仅更新字段,如果没有值或者它是 null 否则保持原样 - Mongoose findOneAndUpdate only update fields if there is no value or it's null otherwise leave as it is 通过检查值是否存在来应用 css - apply css by checking if value exists 如果存在变量,则显示输入文本字段值,否则显示占位符 - If variable exists, display input textfield value, otherwise display placeholder 如果存在Javascript更新数组值,否则将新数组推送到对象 - Javascript update array value if exists otherwise push new array to object ZCCADCDEDB567ABAE643E15DCF0974E503Z 从查找中忽略列,如果值为 null - Mongoose ignore column from find, if the value is null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM