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?
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?
– Lucas Pletsch
@Lucaspletsch I use a lot
exec
will return aPromise
, can run the query of such a fomaconst query = await mode.find(...).exec()
within a functionasync
– Gonsalo Sousa
if I don’t put exec, then the call to find() method blocks my program execution? That is, it is done synchronously?
– Lucas Pletsch
@Lucaspletsch not the
find
does not block, any of the calls returns athenable
only theexec
returns aPromise
true. depends on the architecture of your project. I can usePromises
:)– Gonsalo Sousa
So if I do simply const query = model.find({ 'attribute': {'$in' : keys?
– Lucas Pletsch
@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.– Gonsalo Sousa
Ah. I get confused with await. But I can simply do model.find(). then((err, Docs) =>{ does something with Docs } also right
– Lucas Pletsch
@Lucaspletsch Perfectly! either way is correct! : ) I updated the answer with more details
– Gonsalo Sousa
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?
– Lucas Pletsch
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?
– Lucas Pletsch
I’ll change the question
– Lucas Pletsch
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– Gonsalo Sousa