1

i am trying to do some queries to my db... but i am new in mongodb and i dont know what operator i have to use, or maybe i just do not know how to do it.

i have a collection like this.

const userSchema= new Schema({
    user: { type: String },
    object: { type: String }
})

then i receive in my server a query like this

{
users: ['John', 'Michael', 'Peter'],
objects: ['Object1','Object2','Object3','Object4', 'Object5']
}

so.. in my controller i do this to find...

userModel.find({ user: { $in: req.body.users}, object: { $in: req.body.objects})
        .then((users)=>{
          res.json(users)
        })

Ok, this is working... but, in the case that one of the arrays Users or Objects is empty, it doesn't find nothing... so, how i can handle it? there is any operator that can find all if the array is empty or something?

for example.. if the query comes like this.

{
users: ['John', 'Michael', 'Peter'],
objects: []
}

i would like to find the users in my Users array even if i dont receive any object.

Any help? thank you in advance

2
  • I think you are looking for the $or operator Commented Mar 17, 2019 at 14:05
  • with the $or operator i dont get the result that i expect, because it finds all users and all objects in the model and i just want to find the users that has those objects... damn sorry maybe i am not explaining it well Commented Mar 17, 2019 at 14:15

1 Answer 1

2

You have to create custom match criteria

const query = {
  fieldName: { $gte: ..., $lte: ... }
}
if (req.body.users.length > 0) {
  query.users = req.body.users
}
if (req.body.objects.length > 0) {
  query.objects = req.body.objects
}

userModel.find(query).then((users) => {
  console.log(users)
})
Sign up to request clarification or add additional context in comments.

6 Comments

but.. if req.body.users and objects is an array??
So what? Please try it and then ask a question.
thank you, it works! but i have other question... in case that i want to filter in a date range... i am using { $gte : date: req.body.dateFrom, $lt: date: req.body.dateTo } ... How can i add it to this query object?
Add that criteria in the first part inside query const query = { ... }
mmm it is not finding well.. i think something is wrong with my sintax... where should i add the operators $gte and $lt?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.