Warm tip: This article is reproduced from stackoverflow.com, please click
mongodb node.js

Sort by Started Letter

发布于 2020-03-27 10:28:12

get data by started letter form mongodb using nodejs

let letter = req.params.letter || 'a';

let allMoviesStartedWithLetter = await Movies.find({name : {$regex : 
'^{letter}', $options: 'i'}}).count();

Want to pass letter variable to $regex anyway to do this?

Questioner
Hasitha Chandula
Viewed
87
willis 2019-07-03 23:16

Use the RegExp constructor to make your regular expression:

new RegExp(`^${letter}`, "i")

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.