我如何在猫鼬上使用“LIKE”运算符?

问题描述 投票:7回答:3

当我使用mongoose进行查询时,我遇到了问题。编码遵循此Mongoose.js: Find user by username LIKE value。但它返回空白。

我的代码返回空白。

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

我试过这个回归空白似乎。

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

但我试过这是有效的

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

为什么我使用变量然后返回空白?

node.js mongodb mongoose
3个回答
17
投票

在mongodb中使用$regex

how to use regex

select * from table where abc like %v%

在蒙戈

 var colName="v";
 models.customer.find({ "abc": { $regex: '.*' + colName + '.*' } },
   function(err,data){
         console.log('data',data);
  });

你的查询看起来像

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

1
投票

您可以使用RegExp对象生成带有变量的正则表达式,如果希望搜索不区分大小写,请添加“i”标志。

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

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

0
投票

或者只是简单

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

我不区分大小写

© www.soinside.com 2019 - 2024. All rights reserved.