node.js - MongoDB 正则表达式不一致

标签 node.js mongodb mongoose robo3t

这是测试用例:

db.test.insert({ name: "john"});
db.test.insert({ name: "donny"});
db.test.insert({ name: "lenny"});

db.test.find({ name: { $regex: /^((?!nn)[\s\S])*$/}}); //works fine, returns only john
db.test.find({ name: { $regex: new RegExp("/^((?!nn)[\s\S])*$/")}}); //returns nothing

正则表达式应该返回不包含“nn”的对象,但在使用 RegExp 对象时它不起作用。我使用 Robomongo 对此进行了测试。

知道为什么吗?

最佳答案

使用 new RegExp 时,请勿包含前导和尾随 / 字符。这些仅与 JavaScript 中的文字表示法一起使用。您还需要转义字符串中的反斜杠。

db.test.find({ name: { $regex: new RegExp("^((?!nn)[\\s\\S])*$")}});

关于node.js - MongoDB 正则表达式不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26260904/

相关文章:

node.js - 方法 "collection.find()"最多接受两个参数

mongodb - 在客户端暂停/恢复 MongoDB Realm 同步的解决方法或方法?

MongoDB 使用错误的索引

javascript - 如何在 mongodb (mongoose) 中覆盖子文档的数组属性

node.js - 在 Mongoose 中填充 + 聚合

node.js - 如何授权安装Electron应用程序?

node.js - Azure无服务器函数: input binding DataType "stream" not supported

javascript - 我在使用 Node js 在 debian 中运行 js 脚本时遇到问题

javascript - 将 Date 参数作为本地时间提供给 mongoose 查询

node.js - 如何连接本地网络内的另一台机器mongodb数据库?