How can I use the "LIKE" operator on a mongoose?

I have a problem when I request the use of mongoose.I, following this Mongoose.js: Find the user by username LIKE value . But it returns empty.

This my code returns empty.

 var promise = UserSchema.find({name: /req.params.keyword/ }).limit(5);

I tried to have this return empty.

var n = john; var promise = UserSchema.find({name: /n/ }).limit(5);

But I tried that it works

 var promise = UserSchema.find({name: /john/ }).limit(5);

Why do I use a variable and then return empty?

+7
source share
3 answers

use $regexin 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 request looks like

var name="john";
UserSchema.find({name: { $regex: '.*' + name + '.*' } }).limit(5);
+17
source

RegExp, , 'i', , .

const mongoose = require('mongoose');
const User = mongoose.model('user');

const userRegex = new RegExp(userNameVariable, 'i')
return User.find({name: userRegex})
+1

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

I'm for case insensitive

0
source

Source: https://habr.com/ru/post/1676105/


All Articles