Skip to content

Commit

Permalink
fix(populate): support clone option with lean
Browse files Browse the repository at this point in the history
Fix #8761
Fix #8760
  • Loading branch information
vkarpov15 committed Apr 11, 2020
1 parent c95a2f1 commit b107d90
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/helpers/populate/assignRawDocsToIdStructure.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
'use strict';

const leanPopulateMap = require('./leanPopulateMap');
const modelSymbol = require('../symbols').modelSymbol;
const utils = require('../../utils');

module.exports = assignRawDocsToIdStructure;

Expand Down Expand Up @@ -55,7 +57,13 @@ function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, re
doc = resultDocs[sid];
// If user wants separate copies of same doc, use this option
if (options.clone) {
doc = doc.constructor.hydrate(doc._doc);
if (options.lean) {
const _model = leanPopulateMap.get(doc);
doc = utils.clone(doc);
leanPopulateMap.set(doc, _model);
} else {
doc = doc.constructor.hydrate(doc._doc);
}
}

if (recursed) {
Expand Down
51 changes: 51 additions & 0 deletions test/model.populate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9273,4 +9273,55 @@ describe('model: populate:', function() {
assert.ok(doc.items[0].populated('child'));
});
});

describe('gh-8760', function() {
it('clone with lean creates identical copies from the same document', function() {
const userSchema = new Schema({ name: String });
const User = db.model('User', userSchema);

const postSchema = new Schema({
user: { type: mongoose.ObjectId, ref: 'User' },
title: String
});

const Post = db.model('BlogPost', postSchema);

return co(function*() {
const user = yield User.create({ name: 'val' });
yield Post.create([
{ title: 'test1', user: user },
{ title: 'test2', user: user }
]);

const posts = yield Post.find().populate({ path: 'user', options: { clone: true } }).lean();

posts[0].user.name = 'val2';
assert.equal(posts[1].user.name, 'val');
});
});

it('clone with populate and lean makes child lean', function() { {
const isLean = v => v != null && !(v instanceof mongoose.Document);

const userSchema = new Schema({ name: String });
const User = db.model('User', userSchema);

const postSchema = new Schema({
user: { type: mongoose.ObjectId, ref: 'User' },
title: String
});

const Post = db.model('BlogPost', postSchema);

return co(function*() {
const user = yield User.create({ name: 'val' });

yield Post.create({ title: 'test1', user: user });

const post = yield Post.findOne().populate({ path: 'user', options: { clone: true } }).lean();

assert.ok(isLean(post.user));
});
}});
});
});

0 comments on commit b107d90

Please sign in to comment.