Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(document): make $clone avoid converting subdocs into POJOs #14395

Merged
merged 3 commits into from Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/document.js
Expand Up @@ -4735,7 +4735,7 @@ Document.prototype.$clone = function() {
const clonedDoc = new Model();
clonedDoc.$isNew = this.$isNew;
if (this._doc) {
clonedDoc._doc = clone(this._doc);
clonedDoc._doc = clone(this._doc, { retainDocuments: true });
}
if (this.$__) {
const Cache = this.$__.constructor;
Expand Down
11 changes: 11 additions & 0 deletions lib/helpers/clone.js
Expand Up @@ -41,6 +41,17 @@ function clone(obj, options, isArrayChild) {
if (options && options._skipSingleNestedGetters && obj.$isSingleNested) {
options = Object.assign({}, options, { getters: false });
}
if (options != null && options.retainDocuments != null && obj.$__ != null) {
vkarpov15 marked this conversation as resolved.
Show resolved Hide resolved
const clonedDoc = obj.$clone();
if (obj.__index != null) {
clonedDoc.__index = obj.__index;
}
if (obj.__parentArray != null) {
clonedDoc.__parentArray = obj.__parentArray;
}
clonedDoc.$__parent = obj.$__parent;
return clonedDoc;
}
const isSingleNested = obj.$isSingleNested;

if (isPOJO(obj) && obj.$__ != null && obj._doc != null) {
Expand Down
21 changes: 21 additions & 0 deletions test/document.test.js
Expand Up @@ -12070,6 +12070,27 @@ describe('document', function() {
assert.strictEqual(clonedDoc.$session(), session);
});

it('$clone() with single nested and doc array (gh-14353) (gh-11849)', async function() {
const schema = new mongoose.Schema({
subdocArray: [{
name: String
}],
subdoc: new mongoose.Schema({ name: String })
});
const Test = db.model('Test', schema);

const item = await Test.create({ subdocArray: [{ name: 'test 1' }], subdoc: { name: 'test 2' } });

const doc = await Test.findById(item._id);
const clonedDoc = doc.$clone();

assert.ok(clonedDoc.subdocArray[0].$__);
assert.ok(clonedDoc.subdoc.$__);

assert.deepEqual(doc.subdocArray[0], clonedDoc.subdocArray[0]);
assert.deepEqual(doc.subdoc, clonedDoc.subdoc);
});

it('can create document with document array and top-level key named `schema` (gh-12480)', async function() {
const AuthorSchema = new Schema({
fullName: { type: 'String', required: true }
Expand Down