Skip to content

Commit 35e90da

Browse files
authored
Merge branch 'Automattic:master' into patch-1
2 parents 8d6422b + f98b463 commit 35e90da

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

lib/model.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4472,7 +4472,7 @@ function _assign(model, vals, mod, assignmentOpts) {
44724472
rawOrder[key].push(i);
44734473
} else if (isVirtual ||
44744474
rawDocs[key].constructor !== val.constructor ||
4475-
String(rawDocs[key]._doc._id) !== String(val._doc._id)) {
4475+
(rawDocs[key] instanceof Document ? String(rawDocs[key]._doc._id) : String(rawDocs[key]._id)) !== (val instanceof Document ? String(val._doc._id) : String(val._id))) {
44764476
// May need to store multiple docs with the same id if there's multiple models
44774477
// if we have discriminators or a ref function. But avoid converting to an array
44784478
// if we have multiple queries on the same model because of `perDocumentLimit` re: gh-9906

test/model.populate.test.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11048,4 +11048,52 @@ describe('model: populate:', function() {
1104811048
assert.equal(pet1.owner.name, 'Alice');
1104911049
assert.equal(pet2.owner.name, 'Alice');
1105011050
});
11051+
11052+
it('makes sure that populate works correctly with duplicate foreignField with lean(); (gh-14794)', async function() {
11053+
const authorSchema = new mongoose.Schema({
11054+
group: String,
11055+
name: String
11056+
});
11057+
11058+
const postSchema = new mongoose.Schema({
11059+
authorGroup: String,
11060+
title: String,
11061+
content: String
11062+
});
11063+
11064+
const Author = db.model('Author', authorSchema);
11065+
const Post = db.model('Post', postSchema);
11066+
11067+
await Author.create({ group: 'AUTH1', name: 'John Doe' });
11068+
await Author.create({ group: 'AUTH2', name: 'Jane Smith' });
11069+
await Author.create({ group: 'AUTH2', name: 'Will Jons' });
11070+
11071+
await Post.create({
11072+
authorGroup: 'AUTH1',
11073+
title: 'First Post',
11074+
content: 'Content 1'
11075+
});
11076+
11077+
await Post.create({
11078+
authorGroup: 'AUTH2',
11079+
title: 'Second Post',
11080+
content: 'Content 2'
11081+
});
11082+
11083+
const posts = await Post.find()
11084+
.populate({
11085+
path: 'authorGroup',
11086+
model: 'Author',
11087+
select: { _id: 1, name: 1 },
11088+
foreignField: 'group'
11089+
})
11090+
.select({ _id: 1, authorGroup: 1, title: 1 })
11091+
.lean();
11092+
11093+
for (const post of posts) {
11094+
assert.ok(post.authorGroup._id instanceof mongoose.Types.ObjectId);
11095+
assert.ok(typeof post.authorGroup.name === 'string');
11096+
}
11097+
assert.equal(posts.length, 2);
11098+
});
1105111099
});

0 commit comments

Comments
 (0)