English 中文(简体)
与Norde的Regex一起的Mongo Query 与JS合作开展一个VAREEBL行动
原标题:Mongo Query with Regex in Node JS operating ON A VARIABLE

我有一个问题。 我想用像常规关系 Db 一样的方法, 在我的节点 JS 文件中查询我的MongoDB。 问题是我想要的东西不是字面上的... 这是一个变量! 我还没有找到这样做的好办法。 我拍到的“ 第一次尝试” 镜头是:

var result = postData.replace(/+/g,   ).substring(5);
db.testlogwiki.find({"line_text" : /result/ };
//predictably only matches to the literal "result" as opposed to my variable

rologwiki 是用 mongo 制成的... 我用它运行着, 它用“ 线性_ text” 输入 mach 到 db 条目, 包含“ 结果” 字面上 。

这似乎是一个非常简单的问题...

最佳回答

试试这个:

db.testlogwiki.find({"line_text" : new RegExp(result) };
问题回答

两者都将有效

db.testlogwiki.find({"line_text" : new RegExp(result,  i ) }; // to make this case insensitive 

db.testlogwiki.find( { line_text: { $regex: result[, $options:  i ] } } );

其它所有解答都可能失败, 取决于您输入变量

您可以像其他人表示的那样使用 RegExplus, 但是您必须避开特殊的 Regex 字符, 否则这可能会失败 。

Lodash有这样做的功能(如果你没有使用它,你也许应该使用它,它会增加许多糖,但即使在ES6+标准中都没有)

https://lodash.com/docs#escapeRegExp" rel=“不跟随 nofollow noreferrer>>https://lodash.com/docs#escapeRegExp

db.COLLECTION.find({FIELD_NAME: new RegExp(_.escapeRegExp(VAR), i ) };

您也可以使用 $regex 选项。

db.testlogwiki.find( { line_text: { $regex: result[, $options:  i ] } } );




相关问题
Access DB Ref MongoDB

Whats the best way to access/query a DB Ref: UPDATE: users: name, groupref : {$ref:"groups",$id:"ObjectId ..." } } groups: name, topic, country,...,.. Assumption is that user belongs to only one ...

MongoDB nested sets

What re the best practices to store nested sets (like trees of comments) in MongoDB? I mean, every comment can have a parent comment and children-comments (answers). Storing them like this: { ...

MongoMapper and migrations

I m building a Rails application using MongoDB as the back-end and MongoMapper as the ORM tool. Suppose in version 1, I define the following model: class SomeModel include MongoMapper::Document ...

MongoDB takes long for indexing

I have the following setup: Mac Pro with 2 GB of RAM (yes, not that much) MongoDB 1.1.3 64-bit 8 million entries in a single collection index for one field (integer) wanted Calling .ensureIndex(...) ...

Storing and accessing large amounts of data

My application creates pieces of data that, in xml, would look like this: <resource url="someurl"> <term> <name>somename</name> <frequency>somenumber</...

热门标签