Mongoose发现或条件不按预期工作

时间:2017-05-17 15:24:39

标签: arrays node.js mongodb mongoose schema

我想查找字符串是否存在于架构中{ ... "nextUpDisplay":false, // NOTE: Only added as of JW 7.10.1 "visualplaylist":false, // Added as of JW 7.0.1, but then removed (from documentation) when the playlist changed to overlay style in JW 7.7.0 - should still function though ... } 内的shop_namename中。

这是查询

food

这是我的架构

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_name

中显示与字符串匹配的记录

只有当字符串包含在元素中时,上面才给出了记录。如何检查food.name,即如果shop_name或food.name匹配则应显示

1 个答案:

答案 0 :(得分:0)

我认为您需要将条件置于$or数组中。

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

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

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

Another reference

相关问题