Skip to content

Follow up to "populated documents get saved as strings" #14827

Closed
@fardolieri

Description

@fardolieri

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.5.2

Node.js version

20.15.1

MongoDB server version

7.0.12

Typescript version (if applicable)

No response

Description

There is an edge case that we missed in #14759. When calling populate on a document the _id is again stored as a string in the DB.

I was able to track it down to this line. But this may not be the whole picture.

 function convertTo_id(val, schema) { 
   if (val != null && val.$__ != null) { 
-    return val._id; 
+    return val._doc._id;
   } 

Steps to Reproduce

It's the same example as in #14759 but I added pet.populate('owner') before pet.save().

mongoose.Schema.ObjectId.get(
  value => {
    if (value?.constructor?.name?.toLowerCase() === 'objectid') return String(value)
    return value
  }
)

const ownerSchema = new mongoose.Schema({ name: 'String' })
const petSchema = new mongoose.Schema({
  name: 'String',
  owner: { type: 'ObjectId', ref: 'owner' }
})

const Owner = mongoose.model('owner', ownerSchema)
const Pet = mongoose.model('pet', petSchema)

const owner = new Owner({ name: 'Alice' })
const pet = new Pet({ name: 'Kitty', owner: owner })

await owner.save()

console.log(typeof pet._doc.owner.$__.wasPopulated.value) // object 😀
await pet.populate('owner') // This breaks it 💥💥💥💥💥💥💥💥💥💥
console.log(typeof pet._doc.owner.$__.wasPopulated.value) // string 🙁

await pet.save()

/**
 * The property 'owner' of 'pet' has unexpectedly been saved
 * as a string into the mongoDB instead of ObjectId.
 * 
 * No matter how I query for it, mongoose is not
 * able to find it...
 */

const reloadAttempts = await Promise.all([
  Pet.findOne({ owner: owner }),
  Pet.findOne({ owner: owner._id }),
  Pet.findOne({ owner: String(owner._id) }),
  Pet.findOne({ owner: new mongoose.Types.ObjectId(owner._id) }),
])

console.log(reloadAttempts) // Logs [ null, null, null, null ] but shouldn't

Expected Behavior

No response

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