How to pass several parameters to query in Mongoose?

Asked

Viewed 323 times

0

I want to do a Mongodb search with Mongoose (Nodejs), where I want the objects whose url attribute that is a string contains within it at least 1 of the values I have in an array. How could I do that, using only 1 find()?

For example:
Object saved on Mongo: {url:"www.site.com.br/? orange?...}

const chavesDeBusca = [laranja, melancia]
const query =  model.find({url: 1 ou mais valore de chavesDeBusca})

Obviously this code above doesn’t work, but the idea is to do this.

I could use a regex as key value. But I can’t get one to do that. For example:this regex would do the following: "gives match if a string contains one or more elements contained in the keyDeBusca array"

Does the '$in' solve? Apparently not, because the search result comes empty, even after I give exec()

Ideas?

1 answer

2

You can use the operator $in.

const chavesDeBusca = ['laranja', 'melancia']
// cria a query
const query = model.find({ 'atributo': {'$in' : chavesDeBusca } })

// resolver os resultados utilizando then
query.then((error, documents)=> {
    if (error) {
        return console.log(erro)
    }
    // resultados iteraveis em documents
})

// resolver os resultados usando await exec()
// o await tem que estar contido em uma async function
const documents = await query.exec();
// espera pelos resultados e executa a proxima linha
console.log(documents)

Edit: Use the operator $or

const chavesDeBusca = ['laranja', 'melancia']

// mapear o array de busca para `$or`
const chavesDeBuscaMapeado = chavesDeBusca.map(chave => ({
    'atributo' : new RegExp(`.*${chave}.*`, 'ig')
}))
// cria a query
const query = model.find({ '$or' : chavesDeBuscaMapeado })
  • 1

    I’m testing here. But what good is this exec()? I read in the documentation but it’s not clear. The . find() no longer returns the objects resulting from the query?

  • 1

    @Lucaspletsch I use a lot exec will return a Promise, can run the query of such a foma const query = await mode.find(...).exec() within a function async

  • 1

    if I don’t put exec, then the call to find() method blocks my program execution? That is, it is done synchronously?

  • 1

    @Lucaspletsch not the find does not block, any of the calls returns a thenable only the exec returns a Promise true. depends on the architecture of your project. I can use Promises :)

  • So if I do simply const query = model.find({ 'attribute': {'$in' : keys?

  • 1

    @Lucaspletsch It is well possible for more complex queries or with many results, I recommend to use await exec. I will update my reply with more details.

  • 1

    Ah. I get confused with await. But I can simply do model.find(). then((err, Docs) =>{ does something with Docs } also right

  • 1

    @Lucaspletsch Perfectly! either way is correct! : ) I updated the answer with more details

  • When giving console.log(Documents) does not print anything, then I gave a console.log(typeof Documents) and said it was an Object. Then I gave an Object.values(Documents) and also printed nothing. But why is there nothing inside? My search went wrong?

  • Actually like this. The value of the attribute in the database is a string format url. So, the value of the integer attribute will never be "Orange". But it could be www.google.com/orange/juice, for example. $in would still return this object?

  • I’ll change the question

  • If the value in the database is not exactly the de facto search value this query returns an empty object, you can then use the operator $or mapping the search array, I will update the response with more details

Show 7 more comments

Browser other questions tagged

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