Skip to content

[Bug]: $clone() subdocuments have wrong $parent() reference #15901

@AbdelrahmanHafez

Description

@AbdelrahmanHafez

Prerequisites

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

Mongoose version

9.0.1

Node.js version

N/A

MongoDB server version

N/A

Typescript version (if applicable)

N/A

Description

When calling $clone() on a document with subdocument arrays, the cloned subdocuments' $parent() method returns the original parent document instead of the cloned parent document.

Steps to Reproduce

'use strict';
const mongoose = require('mongoose');
const { Schema } = mongoose;
const assert = require('assert');

run();

function run() {
  const addressSchema = new Schema({
    street: String,
    city: String
  });

  const userSchema = new Schema({
    name: String,
    addresses: [addressSchema]
  });

  const User = mongoose.model('User', userSchema);

  const user = new User({
    name: 'Test User',
    addresses: [{ street: '123 Main St', city: 'Boston' }]
  });

  const clonedUser = user.$clone();

  assert.strictEqual(
    clonedUser.addresses[0].$parent(),
    clonedUser,
    'cloned subdocument $parent() should return cloned document'
  );
  console.log('All tests passed');
}

Expected Behavior

After $clone(), the cloned subdocuments' $parent() should return the cloned parent document, not the original parent document.

const clonedUser = user.$clone();
clonedUser.addresses[0].$parent() === clonedUser; // should be true
clonedUser.addresses[0].$parent() === user; // should be false

Metadata

Metadata

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