I am new to programming and building my first full stack application. In my application I have two entities, Branches and Accounts. Branches names are alphanumerical strings whereas the Accounts are just numbers for example 116003183, 16582368. The scenario is that when a user types in a first few letters of the Branch all the matching results show up. I am unable to do the same with Accounts as that is all numbers. I looked up on few sites that you can use [0-9] but I can't figure out how would I implement that code. Here's my code. Any Help or leads would be appreciated.
router.get('/', async (req, res) => {
let query = Account.find()
if (req.query.name != null && req.query.name != ''){
query= query.regex('name',new RegExp(req.query.name))
}
try{
const accounts = await query.exec()
res.render('accounts/index',{
accounts: accounts,
searchOptions:req.query
})
}
catch(err) {
res.redirect('/')
}
})
CodePudding user response:
Using the $expr
-operator, you can build a query that converts the account name field of type number
to a string and then do a regex match on that field:
// ...
const query = {};
if (req.query.name != null && req.query.name != ''){
query.$expr = {
"$regexMatch": {
"input": {"$toString": "$name"},
"regex": new RegExp(req.query.name)
}
}
}
const accounts = await Account.find(query);
// ...