【问题标题】:Mongoose $regex doesn't work with new RegExp?Mongoose $regex 不适用于新的 RegExp?
【发布时间】:2016-10-13 02:06:30
【问题描述】:

我在使用 Mongoose 进行 $regex 查询时遇到问题;

以下工作正常:

Media.count(
    { "filename" : 
    { $regex: /placeholder(-)?(\w+.)?.(\w+)?$/gm } }, 
    function(err, res){
...

以下不起作用:

var xp = new RegExp("placeholder(-)?(\w+.)?.(\w+)?$", "gm")

Media.count(
    { "filename" : 
    { $regex: xp } }, 
    function(err, res){
...

我也尝试了以下也不起作用:

var xp = new RegExp("placeholder(-)?(\w+.)?.(\w+)?$")

Media.count(
    { "filename" : 
    { $regex: xp, $options: 'gm' } }, 
    function(err, res){
...

出于某种原因,我觉得 Mongoose 不接受 RegExp 对象?我遇到的问题是我需要用变量替换“占位符”,因此我需要使用 RegExp 来完成这项工作......

以前有人遇到过这个问题

【问题讨论】:

    标签: javascript regex node.js mongodb mongoose


    【解决方案1】:

    我刚刚发现我的错误,如果其他人有同样的问题,请在此处添加:

    使用新的 RegExp 时,您需要确保以这种方式转义反斜杠:

    正道:

    var xp = new RegExp("placeholder(-)?(\\w+.)?.(\\w+)?$")
    

    错误的方式:

    var xp = new RegExp("placeholder(-)?(\w+.)?.(\w+)?$")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-01
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      • 2017-02-01
      • 2016-02-28
      相关资源
      最近更新 更多