Reputation: 902
I have a problem when i query using mongoose.I coding follow this Mongoose.js: Find user by username LIKE value. But it return blank.
This my code return blank.
var promise = UserSchema.find({name: /req.params.keyword/ }).limit(5);
I tried this return blank seem.
var n = john; var promise = UserSchema.find({name: /n/ }).limit(5);
But i tried this is working
var promise = UserSchema.find({name: /john/ }).limit(5);
Why I use variable then return blank?
Upvotes: 54
Views: 77784
Reputation: 351
select * from table where abc like %_keyword%
in mongo it is
const list = await ProductModel.find({{ pname :{ $regex : '.*'+ _keyword + '.*' }});
here _keyword
can be any text eg. fruit, pen, etc. as i am searching products model.
Upvotes: 2
Reputation: 2905
You can run a regex lookup with dynamic values using RegExp
:
var promise = UserSchema.find({name: new RegExp(req.params.keyword, 'i') }).limit(5);
Notice the 'i'
option for case insensitivity.
Upvotes: 1
Reputation: 271
Without aggregate
it didn't work for me. But this did:
db.dbname.aggregate([{ "$match" : {"name" : { $regex: '.*SERGE.*', $options: 'i' } }}, { $sort: { "createdTime" : -1 }} ]).pretty()
Upvotes: 1
Reputation: 437
This is how i have done it to find if search string present in name/email. Hope it helps someone.
const getPeerSuggestions = async (req, res, next) => {
const { search } = req.query;
const rgx = (pattern) => new RegExp(`.*${pattern}.*`);
const searchRgx = rgx(search);
const peers = await User.find({
$or: [
{ name: { $regex: searchRgx, $options: "i" } },
{ email: { $regex: searchRgx, $options: "i" } },
],
})
.limit(5)
.catch(next);
res.json(peers);
};
Upvotes: 15
Reputation: 7078
Or just simply
const name = "John"
UserSchema.find({name: {$regex: name, $options: 'i'}}).limit(5);
i for case-insensitive
Upvotes: 31
Reputation: 1117
You can use the RegExp object to make a regex with a variable, add the 'i' flag if you want the search to be case insensitive.
const mongoose = require('mongoose');
const User = mongoose.model('user');
const userRegex = new RegExp(userNameVariable, 'i')
return User.find({name: userRegex})
Upvotes: 10
Reputation: 2257
use $regex
in mongodb
example
select * from table where abc like %v%
in mongo
var colName="v";
models.customer.find({ "abc": { $regex: '.*' + colName + '.*' } },
function(err,data){
console.log('data',data);
});
Your query look like
var name="john";
UserSchema.find({name: { $regex: '.*' + name + '.*' } }).limit(5);
Upvotes: 91