喜欢mongoose

使用正则expression式(只有/最好)的方式来使用LIKE (如SQL中)在mongoose中的function?

我的例子:

 Thing.find({ name: new RegExp('^' + req.body.name, "i") }) .limit(5) .sort('-rating') .lean(true) .exec( function (err, things) { res.send(things); } ); 

由于这是MongoDB唯一的方法(除了使用一个文本索引有一些约束),这是最好的方法。

我认为你只能用javascript实现相同的行为。 像下面的东西会做LIKERegExp的转换。

(没有testing,所以可能不工作。)

 function createLikeRegex(query) { query = query .replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') .replace(/(^|[^\\\])%#/g, '\\$&'); if (! query.startsWith('%')) { query = '^' + query; } if (! query.endsWith('%')) { query += '$'; } return new RegExp(query, 'i'); }