Javascript 使用正则表达式进行Mongoose查找不起作用
我正在用Javascript 使用正则表达式进行Mongoose查找不起作用,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我正在用Mongoose在MongoDB中进行选择,如下所示: SQL 从名称为“%Sorv%”的产品中选择*; 因此,我有一个产品模型: mongoose.model('Products' , new mongoose.Schema({ name: {type: String, default: ''}, price: {type: Number, default: 0}, prices: [Number]
Mongoose
在MongoDB
中进行选择,如下所示:
SQL
从名称为“%Sorv%”的产品中选择*;
因此,我有一个产品
模型:
mongoose.model('Products'
, new mongoose.Schema({
name: {type: String, default: ''},
price: {type: Number, default: 0},
prices: [Number]
})
, 'products');
如果我尝试在产品
模型中获取所有注册表,它将返回正确的:
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版本I使用的是:
console.log(mongoose.version);
4.2.5
我遇到了同样的问题,设法解决了它,如下所述(如中所述)
我遇到了同样的问题,设法解决了它,如下所述(如中所述)
如果您采用这种方法:Product.find({name:new RegExp('sorv','i')})
-它有效吗?(忽略大小写意味着不能使用索引,您将导致集合扫描)Product.find({name:new RegExp('sorv','i')})
为我返回一个空数组,如果您在mongo
命令行中尝试相同的find命令会怎么样db.products.find({name:/sorv/i})
-有什么发现吗?还有,你有什么猫鼬版本?根据版本的不同,您可能需要执行find().exec().then()而不是find().then()可以通过mongoose.set('debug',true)将debug设置为true
并将输出添加到您的问题中?@jpaljasma如果我通过命令行执行查询,返回的结果是什么如果您采用这种方法:Product.find({name:new RegExp('sorv','I')})
-是否有效?(忽略大小写意味着不能使用索引,您将导致集合扫描)Product.find({name:new RegExp('sorv','i')})
为我返回一个空数组,如果您在mongo
命令行中尝试相同的find命令会怎么样db.products.find({name:/sorv/i})
-有什么发现吗?还有,你有什么猫鼬版本?根据版本的不同,您可能需要执行find().exec().then()而不是find().then()可以通过mongoose.set('debug',true)将debug设置为true
并将输出添加到您的问题?@jpaljasma如果我通过命令行执行查询,是否返回结果
Product.find({ name: { $regex: 'sorv', $options: 'i'}})