Skip to content

Mongoose plugin does not cast the query before execution #312

Open
@SeanLMcCullough

Description

@SeanLMcCullough

I came across this issue today when querying a Mongoose schema with a ref and ObjectId to another collection.
Usually, Mongoose will cast the query before execution, and convert all ObjectId properties to ObjectIds before executing the query. When using the mongoose plugin, this does not happen, so fields that should be ObjectIds are instead queried as strings. The outcome is that no documents will be found.

Example:

const Model = new mongoose.Schema({
  otherId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'OtherModel',
    index: true
  }
})

const options = {
  query: {
    { otherId: '619f1683a899a80029b18989' }
  }
}

const result = await Model.paginate(options)
console.log(result.results) // Length is 0 because otherId is handled as a string, not ObjectId.

The mongoose plugin should ideally cast the query before executing the find method. For example, the following casting works before executing the query:

options.query = new mongoose.Query().cast(Model, options.query)

Having the mongoose plugin handle this internally would likely be a good enhancement, so all of the Mongoose special sauce is handled ahead of the query on the collection.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions