-1

I have a Client schema that contains one of the properties: services, which is an array.

Client.Schema

const clientSchema = mongoose.Schema({
  compName: { type: String, required: true },
  ....
  ....
  services: [{
    servName: String,
    servCat: String,
    freq: String,
    fees: Number,
    dueDay: Number,
    dueMonth: Number,
  }]
});

I need to write a query which will return all the clients that have at least one service in the services array. I tried the below query but it gives me an error The expression evaluated to a falsy value:↵↵ assert.ok(!isNaN(val))

mongoose Query

const clients = await Client.find({ 'services': { $size: { $gt: 0} } }).lean().sort('compName');

what would be the correct mongoose query for this? pls help.

Mohammad Yaser Ahmadi
  • 4,664
  • 3
  • 17
  • 39
hemant
  • 377
  • 1
  • 2
  • 13
  • Does this answer your question? [Mongoose find all documents where array.length is greater than 0 & sort the data](https://stackoverflow.com/questions/31677061/mongoose-find-all-documents-where-array-length-is-greater-than-0-sort-the-data) – Mohammad Yaser Ahmadi Feb 11 '21 at 16:12

1 Answers1

1

You can check the documents where exists value 0 (i.e. exists at lest one document) in this way:

db.collection.find({
  "services.0": {
    "$exists": true
  }
})

Example here

Another option is to use $expr which, as said into documentations:

Allows the use of aggregation expressions within the query language.

So you can do this query

db.collection.find({
  "$expr": {
    "$gte": [{$size: "$services"},1]
  }
})

Example here

Using mongoose is the same query:

var find = await yourModel.find({"$expr": {
    "$gte": [{$size: "$services"},1]
  }}).lean().sort('compName');

or

var find = await yourModel.find({"services.0": {
    "$exists": true
  }}).lean().sort('compName');
J.F.
  • 13,927
  • 9
  • 27
  • 65