【问题标题】:Mongoose find with regex is not working使用正则表达式的猫鼬查找不起作用
【发布时间】:2016-10-02 06:26:22
【问题描述】:

我正在尝试在MongoDBMongoose 中进行选择,如下所示:

SQL SELECT * FROM PRODUCTS WHERE NAME LIKE '%Sorv%';

所以,我有一个Product 模型:

mongoose.model('Products'
    , new mongoose.Schema({
            name: {type: String, default: ''},
            price: {type: Number, default: 0},
            prices: [Number]
        })
    , 'products');

如果我尝试在Product 模型中获取所有寄存器,它将返回正确:

Product.find()
        .then(function (result)
        {
            var names = result.map(function (item)
            {
                return item.name;
            });
            // return ["Sorvete", "Sorvete Morango", "Sorvete Morango", "Sorvete", "Sorvete"]
            console.log(names);
        });

为什么当我使用Regex 查找时,根据Mongoose 文档,它返回一个空数组?

Product.find({name: /Sorv/})
        .then(function (result)
        {
            // return a empty array: []
            console.log(result);
        });

如果我设置mongoose.set('debug', true); 并执行闲置代码:

Product.find({ name: new RegExp('sorv', 'i') })
.then(function(r){
    console.log(r);
})

这对我来说是休闲错误:

[0;36mMongoose:[0m products.find({ name: [32m'/sorv/i'[39m }) { fields: [90mundefined[39m } 

但是如果我在 mongo 命令中执行查询,它会返回正确的结果

//Return correct results
db.products.find({name: /sorv/i})

我使用的 Mongoose 版本是:

console.log(mongoose.version);
4.2.5

【问题讨论】:

  • 如果您采用这种方法会怎样:Product.find({ name: new RegExp('sorv', 'i') }) - 它有效吗? (忽略大小写意味着不能使用索引,您将导致集合扫描)
  • Product.find({ name: new RegExp('sorv', 'i') }) 也为我返回一个空数组
  • 如果您在mongo 命令行中尝试相同的查找命令会怎样? db.products.find({name:/sorv/i}) - 得到什么?另外,你有什么猫鼬版本?根据版本,您可能需要执行 find().exec().then() 而不是 find().then()
  • 您可以通过mongoose.set('debug', true); 将调试设置为true 并将输出添加到您的问题中吗?
  • @jpaljasma 如果我通过命令行执行查询,是返回结果

标签: javascript node.js mongodb mongoose


【解决方案1】:

我有同样的问题,设法解决它如下(如here 中所述)

Product.find({ name: { $regex: 'sorv', $options: 'i'}})

【讨论】:

    猜你喜欢
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    相关资源
    最近更新 更多