Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can use "LIKE" operator on mongoose?

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?

like image 909
devnext Avatar asked May 02 '17 02:05

devnext


People also ask

What does lean () do Mongoose?

The lean() function tells mongoose to not hydrate query results. In other words, the results of your queries will be the same plain JavaScript objects that you would get from using the Node. js MongoDB driver directly, with none of the mongoose magic.

What does exec () do Mongoose?

In mongoose, exec method will execute the query and return a Promise.

What is $in in Mongoose?

The value of the $in operator is an array that contains few values. The document will be matched where the value of the breed field matches any one of the values inside the array.

What does save () do in Mongoose?

Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.


2 Answers

use $regex in mongodb

how to use regex

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); 
like image 152
kumbhani bhavesh Avatar answered Sep 28 '22 01:09

kumbhani bhavesh


Or just simply

const name = "John" UserSchema.find({name: {$regex: name, $options: 'i'}}).limit(5); 

i for case-insensitive

like image 32
Nux Avatar answered Sep 28 '22 03:09

Nux