简体   繁体   中英

Nodejs - MongoDB findone with exact match but case insensitive

db.collection("accounts").findOne({Nickname: { $regex : new RegExp(player, "i") }}, function(err, result) { }

Is what I currently have, the problem is that I get everything that is a substring of the player variable. But I want only exact, albeit case-insensitive matches.

Prefix player with ^ and suffix with $, so that it matches the entire string

"^" + player + "$"

^ matches the start of the string

$ matches the end of the string

Reference for boundary regex characters

So with this expression you're saying "find me Nickname which starts and ends with this string" ie the entire string

Your regex actually asks for a substring. To ask for an exact string:

new RegExp("^" + player + "$", "i")

(Keep everything else the same.)

The ^ matches the beginning of the input, the $ matches the end. This way, any substrings won't match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM