在 MongoDB 查询中使用 javascript 变量作为 $regex 的值 [英] Use javascript variable as a value of $regex in MongoDB query
本文介绍了在 MongoDB 查询中使用 javascript 变量作为 $regex 的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将参数传递给 mongo 查询 - 如果我输入文字,它可以正常工作,但是,当我尝试用变量(参数)替换文字时,它会失败
I'm trying to pass arguments into a mongo query - if I type the literal, it works fine, however, when I try to replace the literal with the variable (argument), it fails
想象一个带有事物"的数据集
imagine a data set with "things"
{"thing": {"name":"book","label":"Bobs"}}
{"thing": {"name":"blanket","label":"Bobs"},
{"thing": {"name":"books","label":"Jills"},
{"thing": {"name":"blankets","label":"Jills"},
我有一种方法可以找到书"书"书"书"或毯子"
I have a method to find "Book" "book" "Books" "books" or "blankets"
如果我用文字书"来做这件事 - 它有效
If I do this with the literal 'Book' - it works
function( name, callback ) {
Catalog
.find({ 'thing.name': {"$regex": /Book/, "$options": "i" }})
.exec(callback);
}
但是 - 我希望使用参数名称".
However - I want the argument 'name' to be used.
function( name, callback ) {
Catalog
.find({ 'thing.name': {"$regex": /name/, "$options": "i" } })
.exec(callback);
}
但这不起作用,它似乎在寻找文字名称"而不是传入的值.我如何逃避这个?
But this doesn't work, it appears to be looking for the literal 'name' not the passed in value. how to i escape this?
推荐答案
可以这样做:-
function( name, callback ) {
Catalog
.find({ "thing.name": { $regex: name, $options: "i" }})
.exec(callback);
}
这篇关于在 MongoDB 查询中使用 javascript 变量作为 $regex 的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文