I'm try make a select in MongoDB
with Mongoose
like something this:
SQL SELECT * FROM PRODUCTS WHERE NAME LIKE '%Sorv%';
So, I has a Product
model:
mongoose.model('Products'
, new mongoose.Schema({
name: {type: String, default: ''},
price: {type: Number, default: 0},
prices: [Number]
})
, 'products');
If I'm try get all register in Product
model, it will return correct:
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);
});
Why when I make a find with Regex
, according to Mongoose
document, it return a empty array?
Product.find({name: /Sorv/})
.then(function (result)
{
// return a empty array: []
console.log(result);
});
If I set mongoose.set('debug', true);
and execute fallowing code:
Product.find({ name: new RegExp('sorv', 'i') })
.then(function(r){
console.log(r);
})
This return for me fallowing error:
[0;36mMongoose:[0m products.find({ name: [32m'/sorv/i'[39m }) { fields: [90mundefined[39m }
But if I execute query in mongo command, it return correct result
//Return correct results
db.products.find({name: /sorv/i})
Mongoose version I using is:
console.log(mongoose.version);
4.2.5
我有同样的问题,设法解决它像下面(如描述这里 )
Product.find({ name: { $regex: 'sorv', $options: 'i'}})
The fault is in the regular expression. It appears that you want to return all products whose names contain 'sorv'. You must use '. sorv. ' instead of 'sorv'. The code below works:
Product.find({ name: new RegExp('.*sorv.*', 'i') }) // '.*sorv.*' matches all names that contain 'sorv'.
.then(function(r){
console.log(r);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.