2017-04-12 89 views
1

的数组中的对象领域的“字符串”我的模式是这样的:猫鼬查询找到对象

Collection = new Schema({ 
name: {type: String, required: true}, 
tags: [String], 
movies: [{_id: false, 
      original_title: {type: String}}] 
)}; 

我需要改变下面的查询使用“req.body”(字符串数组)不仅在'标签'数组中找到匹配项,而且还在电影数组中找到与'original_title'字段匹配的项目。

Collection.find({'tags' : { $in : req.body}}, (err, collections) => {   
      if(err){res.status(400).json(err);} 

      if(!collections) 
      { 
       res.status(404).json({message: 'No collections found'}); 
      }else{ 
       res.json(collections); 
      } 
     }).limit(8); 

回答

1

试试这个:

db.collection.find({ 
    $or: [{ 
      'tags': { 
       $in: req.body 
      } 
     }, 
     { 
      'original_title': { 
       $in: req.body 
      } 
     } 
    ] 
}, (err, collections) => { 
    if (err) { 
     res.status(400).json(err); 
    } 

    if (!collections) { 
     res.status(404).json({ 
      message: 'No collections found' 
     }); 
    } else { 
     res.json(collections); 
    } 
}).limit(8); 
+0

这工作,但我有区分大小写的问题。任何想法如何忽略'original_title'条件? – JakePlatford

+1

我知道它可以使用正则表达式完成单个字符串,不确定数组。 但我仍然认为,当你的价值一直处于较低或较高的水平时,存储和搜索价值会更好。 –