Skip to content

Model.hydrate does not always cast Object ID values correctly #11052

Closed
@asabhaney

Description

@asabhaney

Do you want to request a feature or report a bug?

Bug (and backward breaking - looks like the regression was initially introduced in 5.12.4)

What is the current behavior?

The behaviour of Model.hydrate is inconsistent with how it casts String values for fields that should be ObjectIds.

  • If no ref schema path option is specified, the hydration works as expected when an ID string is passed in.
  • If the ref option is set, the hydration fails.

If the current behavior is a bug, please provide the steps to reproduce.

const assert = require('assert')
const mongoose = require('mongoose')
const { Schema } = mongoose

it('Calling `Model.hydrate` does not always cast Object ID values correctly', async () => {
   const bookSchema = new Schema({
      // Removing the `ref: 'author'` option causes the test to pass successfully
      author: { type: mongoose.Types.ObjectId, required: true, ref: 'author' }
   })

   const Book = mongoose.model('book', bookSchema)

   const book = Book.hydrate({
      author: '513bb18e268bb25016131ca6'
   })

   assert(book.author instanceof mongoose.Types.ObjectId)
})

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

node.js: 14.17.6
mongoose: 6.0.14
MongoDB: 4.4.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions