Mohamed Oraby
Mohamed Oraby

Reputation: 1036

Mongoose: how to query by a key of an object

I have a schema that looks like this

const CustomersSchema = new mongoose.Schema({
  merchant:{
    type: mongoose.Schema.Types.ObjectId,
    required:true,
    ref: 'Merchent'
  },
  idCustomer:{
    type: String,
    required: true,
    trim:true,
    //unique: true
  }, 
  customerData:{
   type:Object,
   required:true
  }
});

and customerData looks like

{
   "name": "Other",
   "birthday": null,
   "age": null,
   "createdAt": "2019-04-01T20:01:04.000Z",
   "email": null,
   "visits": 0,
   "payments": "0.00",
   "lastVisit": "2019-12-16T12:58:09.000Z",
}

Is there a way I can query by customerData.name and if it doesn't exist it won't cause errors

Right now I do

let query = {
    merchant: merchant._id,
    'customerData.name': req.query.name
}
Customer.find(query)
  .then(...)

but this way if there is no query.name no documents return

Edit: also regex won't do because I will need to search by numbers(ex: customerData.visits) in the future

Upvotes: 2

Views: 1318

Answers (1)

Ankita Kuchhadiya
Ankita Kuchhadiya

Reputation: 1282

It seems like you need to return the document whether or not you have query.name and if there is query.name the query will consider that and if there is no query.name it will not take that into account. So, you can setup a small logic for that. Something like this:

let query = {
  merchant: merchant._id
};
// we only set the query for the customerData.name if query.name exist
if(req.query.name) {
  query['customerData.name'] = req.query.name;
}
Customer.find(query)
  .then(...)

Upvotes: 5

Related Questions