【问题标题】:Using $regex mongodb query in node js not working在节点 js 中使用 $regex mongodb 查询不起作用
【发布时间】:2015-04-19 10:56:22
【问题描述】:


从节点 js,我尝试根据不区分大小写的关键字检索文档。当我直接从 mongo db 控制台尝试时,我可以看到结果。

db.users.findOne({"displayName":{$regex: /.*abc./, $options:"i"}})

但是当我在节点 js 中尝试相同的操作时,我得到的是空结果。

var selector = { "displayName": {$regex: "/.*abc./", $options:"i"}}

这是因为正则表达式不在 javascript 中。
谁能帮我解决这个问题。

【问题讨论】:

标签: javascript regex node.js mongodb


【解决方案1】:

$regex 值需要是要匹配的字符串模式或正则表达式对象。传递字符串模式时,不要像在 node.js 代码中那样包含 / 分隔符。

所以这些都可以在 node.js 中工作:

var selector = {"displayName": {$regex: ".*abc.", $options:"i"}}

var selector = {"displayName": {$regex: /.*abc./, $options:"i"}}

【讨论】:

    【解决方案2】:

    你能试试这个吗,它对我有用。

    var getValue = "abc";
    
    db.users.findOne({ displayName: new RegExp(regexValue, "i") }, function(err, res) {
      if (err) {
        console.log(err);
      } else {
        console.log(res.length);
      }
    });
    

    【讨论】:

    • 这是唯一一个为我工作的人"mongoose": "4.11.2"
    【解决方案3】:

    在 mongodb 控制台中 试试这个查询

    db.users.findOne({"displayName":{$regex: ".*abc", $options:"i"}})

    在 nodejs 中 var selector = users.find({ "displayName": {$regex: ".*abc", $options:"i"}})

    这里 users = 是一个集合名称

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-13
      • 2018-09-03
      • 2021-03-21
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 2019-08-24
      • 2012-06-09
      相关资源
      最近更新 更多