How to create a search box with Nodejs and Mongodb?

Asked

Viewed 223 times

-1

I am trying to create a search with mongodb using "like" according to this site this site https://bognarjunior.wordpress.com/2015/05/18/consultas-avancadas-com-mongodb/

var results = await Hist.find({'cliente':/Jean/i}).sort({'pago':1, 'hora_saida':0})
    console.log(results)

It works, however I would like to make it work using a variable that comes from my front-end, I tried that way and it didn’t work:

async search(req,res){
    var search = "'cliente':"+'/'+req.body.search+'/i'
    var results = await Hist.find({search}).sort({'pago':1, 'hora_saida':0})
    console.log(results)
},

Remembering that the variable arrives correctly in the back end, but I can not use in the function that queries in the database.

1 answer

0


Note that in your own example you use find({ cliente: /Jean/i }), where find receives the object { cliente: /Jean/i }.

Down below you try again passing { search } as parameter. As the value of search is 'cliente:/${nome}/i', this will result in the object { search: 'cliente:/${nome}/i' }, which is obviously not equivalent to what you wanted.

Another apparent error is that you are trying to use a string as a regular expression. /Jean/i is different from '/Jean/i', the first is a regular expression, the second is just a string. To generate a dynamically regular expression you need to use the function RegExp, in your case, RegExp(req.body.search, 'i')

So by correcting both the key and the value of your object, you would have:

async search(req, res) {
    var search = { cliente: RegExp(req.body.search, 'i') }
    var results = await Hist.find(search).sort({ pago: 1, hora_saida: 0 })
    console.log(results)
}

Or alternatively:

async search(req, res) {
    var cliente = RegExp(req.body.search, 'i')
    var results = await Hist.find({ cliente }).sort({ pago: 1, hora_saida: 0 })
    console.log(results)
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.