Skip to content

Commit

Permalink
fix(document): make $clone avoid converting subdocs into POJOs
Browse files Browse the repository at this point in the history
Re: #14353
  • Loading branch information
vkarpov15 committed Feb 29, 2024
1 parent c02141b commit 4ee3d27
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
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) {
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

0 comments on commit 4ee3d27

Please sign in to comment.