[英]Mongoose find with or condition not working as expected
I want to find whether the string exist either in the shop_name
or name
inside the food
in the schema. 我想查找该字符串是否存在于
shop_name
或架构中food
内部的name
中。
Here is the query 这是查询
dbModel.stores.find({ "food.name": { '$regex': re } }).or([{ 'shop_name': { '$regex': re } }]).exec(function(err, docs) {
if (!err) {
res.status(200).json({
"success": "1",
"message": docs
});
} else {
res.status(200).json({
"success": "0",
"message": "No result found"
});
}
});
Here's my schema 这是我的图式
var storeSchema = {
"area": String,
"food": [{
'name': String,
'description': String
}],
"shop_name": String
};
I want to show the record which matches with the string either in the shop_name
or food.name
我想显示与
shop_name
或food.name
的字符串匹配的记录
The above gives me the record only if the string contains in both the element. 以上仅在字符串包含在两个元素中时给我记录。 How can i get check with
or
ie, If shop_name or food.name was matched then it should display it 我该如何查询
or
,如果shop_name或food.name匹配,则应显示它
I think you need to place your conditions within the $or array. 我认为您需要将条件放入$ or数组中。
Because food
is an array of objects, you may need to use $elemMatch in your first condition. 因为
food
是一组对象,所以您可能需要在第一个条件下使用$ elemMatch 。
I've never done this before, but it would look like: 我以前从未做过,但是看起来像:
dbModel.stores.find({
$or: [
{
food: {
$elemMatch: { name: { $regex: re }}
}
},
{
shop_name: { $regex: re }
}
]
}).exec(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.