Mongoose query doesn't work as expected but works in compass

Viewed 50

This is the relevant part of the schema:

{
  info: {
    // item_info can be undefined
    item_info: {
      enchants: [{name: String, level: Number}]
    }
  }
}

Both info and item_info are separate schemas with _id set to false (dk if this is relevant)

And this is an example query:

{"info.item_info.enchants": {$all: [{name: "growth", level: 5}, {name: "protection", level: 5}]}}

Throwing that query in MongoDB Compass works as expected. Returns all the documents that contain both {name: "growth", level: 5} and {name: "protection", level: 5} in the enchant field

Throwing that query in <ModelName>.find() instead returns all the documents that don't have an item_info field(?)

The same query but with $in instead of $all works as expected (returns the docs that have any one of the elements in the array) and so does directly putting the array in with no operators (returns the docs that have exactly those 2 elements)

The enchants field used to look like this:

// skipping the other fields
enchants: [
  {"protection": 5},
  {"growth": 5}
]

instead of what I have now with name and level fields and the $all operator worked just fine.

Is there any fix or work-around?

1 Answers

Turns out I also changed some things in the schemas.

The enchants field used to be enchants: Array back when it worked fine instead of
enchants: [{"name": String, "name": Number}].

Explicitly setting the array's content type seems to break an $all query on the array.

Related