简体   繁体   中英

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

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(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM