0

In my collection, I have groups where they can limit the members within. I want to query all groups that have enough spaces left by a number given in a search form. I use mongoose and node for my API.

So when in a group are 2 members, the limit 3 and the user searches for 2 places left in a group. This group won't show, but any other.

How do I query this? I already found something like query.$expr = { $gt: [{ $strLenCP: "$members" }, params.searchValue /*2 in my example*/ ] }; but I dont really understand that.

Here my mongoose Schema:

let GroupSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  status: {
    type: String,
    required: true
  },
  game: {
    type: Schema.Types.ObjectId,
    ref: 'Games',
    required: true
  },
  alias: {
    type: String,
    required: true,
    unique: true
  },
  owner: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  range: Number,
  image: String,
  description: String,
  members: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }],
  updated: Date,
  created: Date
});
muuvmuuv
  • 901
  • 2
  • 13
  • 39
  • You're looking at the wrong operator. The `members` property in your documents is an "array". There are well established ways of querying the array length that work in all MongoDB versions. That said, you probably "should" create a document property indicating the length (number of members) if that is the sort of query which is important to you. – Neil Lunn May 07 '18 at 12:03
  • @NeilLunn I tried that answer and updated it to my formula: `query.$where = "(this.members.length - this.range) >" + params.searchValue;` but that doesn't work. – muuvmuuv May 07 '18 at 12:06
  • 1
    You tried the wrong one. Better to use the `$exists` i.e `{ "members.0": { "$exists": true }, "members.2": { "$exists": true } }` would mean an array between 2 and 3 items length. There are also "other" suggestions there which do not use `$where` which are also valid for your case. And comparing to a field in the document is another condition. You really should not and simply store an `"availableSpots"` number which you simply decrement as you add new members to he array anyway. – Neil Lunn May 07 '18 at 12:13

0 Answers0