我正试图从一个变量传递searchTerm,我该如何实现这一点呢?
const mongoquery = { description: { $in: [ /searchTerm/ ] } };
我最初尝试使用:
const mongoquery = { description: { $in: [ `/${searchTerm}/` ] } };
但是,这不起作用,因为'包含在字符串:
{ description: { '$in': [ '/FAB/' ] } }
您可以在searchTerm中使用RegExp,如
const mongoquery = { description: new RegExp(searchTerm, "i") };
对于like搜索,可以使用like as
const mongoquery = { description: new RegExp("^" + searchTerm + "$", "i") };
OR
const mongoquery = { description: new RegExp(searchTerm + "$", "i") };
您可以使用RegExp方法,
const mongoquery = { description: { $in: [ new RegExp(searchTerm) ] } };