【问题标题】:Mongoose find with or condition not working as expected猫鼬发现或条件未按预期工作
【发布时间】:2017-10-17 03:51:58
【问题描述】:

我想查找该字符串是否存在于架构中 food 内的 shop_namename 中。

这里是查询

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"
            });
        }
    });

这是我的架构

var storeSchema = {
    "area": String,
    "food": [{
        'name': String,
        'description': String
    }],
    "shop_name": String
};

我想显示与shop_namefood.name 中的字符串匹配的记录

只有当字符串包含在两个元素中时,上面才会给我记录。我如何使用or 进行检查,即如果 shop_name 或 food.name 匹配,那么它应该显示它

【问题讨论】:

    标签: arrays node.js mongodb mongoose schema


    【解决方案1】:

    我认为您需要将条件放在 $or 数组中。

    因为food 是一个对象数组,所以您可能需要在第一个条件中使用$elemMatch

    我以前从未这样做过,但它看起来像:

    dbModel.stores.find({ 
        $or: [
            { 
               food: { 
                   $elemMatch: { name: { $regex: re }}
               }
            }, 
            { 
               shop_name: { $regex: re }
            }
        ] 
    }).exec(...)
    

    Another reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-03
      • 2021-12-13
      • 2013-11-01
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2016-08-26
      相关资源
      最近更新 更多