Skip to content

_id field for subdocuments array items no longer being set on retrieval #12264

Closed
@ajwootto

Description

@ajwootto

Prerequisites

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

Mongoose version

6.5.2

Node.js version

16.x

MongoDB server version

5.x

Description

In the version of Mongoose I was using before ( 6.0.11 ), if you had data inserted in Mongo that contained a subdocument array containing items without _id fields, Mongoose would fill in those fields with new _ids when the document was retrieved.

On the latest version of Mongoose, that seems to no longer be the case. I'm not sure if this is a deliberate change of behaviour or a regression. See the sample code below:

Steps to Reproduce

import { Schema, model, connect, Types } from 'mongoose'
import * as mongoose from 'mongoose'

interface NestedChild {
    name: string
    _id: Types.ObjectId
}
const nestedChildSchema: Schema = new Schema({ name: String })

interface Parent {
    nestedChild: Types.DocumentArray<NestedChild>
    name?: string
}

const ParentModel = model<Parent>('Parent', new Schema({
    nestedChild: [nestedChildSchema],
    name: String
}))

export async function run() {
    console.log('Running test')
    await connect('mongodb://localhost:27017/')
    const dbConnection = mongoose.connections[0]
    const { insertedId } = await dbConnection.collection('parents').insertOne({
        nestedChild: [{ name: 'foo' }],
        name: 'Parent'
    })

    const parentRaw = await dbConnection.collection('parents').findOne({ _id: insertedId })
    const parentFound = await ParentModel.findOne({ _id: insertedId })

    // this is always undefined
    console.log('raw data', parentRaw?.nestedChild[0]._id)
    // on mongoose 6.0.11 this is an object id
    // on mongoose 6.5.2 this is undefined
    console.log('after retrieval', parentFound?.nestedChild[0]._id)
}

run()

Expected Behavior

Unless this was deliberate, I would expect this behaviour to be unchanged and for mongoose to fill in the _id fields of the subdocuments upon retrieval

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions