Skip to content

Commit 47c3b46

Browse files
committed
fix: set flattenObjectIds to false when calling toObject() for internal purposes
Fix Automattic#14935
1 parent e7d7652 commit 47c3b46

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

lib/model.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,7 @@ const subclassedSymbol = Symbol('mongoose#Model#subclassed');
7575
const { VERSION_INC, VERSION_WHERE, VERSION_ALL } = Document;
7676

7777
const saveToObjectOptions = Object.assign({}, internalToObjectOptions, {
78-
bson: true,
79-
flattenObjectIds: false
78+
bson: true
8079
});
8180

8281
/**

lib/options.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,6 @@ exports.internalToObjectOptions = {
1212
depopulate: true,
1313
flattenDecimals: false,
1414
useProjection: false,
15-
versionKey: true
15+
versionKey: true,
16+
flattenObjectIds: false
1617
};

test/document.test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13926,6 +13926,32 @@ describe('document', function() {
1392613926
cur.subdocs[0] = { test: 'updated' };
1392713927
await savedDoc.save();
1392813928
});
13929+
13930+
it('avoids flattening objectids on insertMany (gh-14935)', async function() {
13931+
const TestSchema = new Schema(
13932+
{
13933+
professionalId: {
13934+
type: Schema.Types.ObjectId
13935+
},
13936+
firstName: {
13937+
type: String
13938+
},
13939+
nested: {
13940+
test: String
13941+
}
13942+
},
13943+
{
13944+
toObject: { flattenObjectIds: true }
13945+
}
13946+
);
13947+
const Test = db.model('Test', TestSchema);
13948+
13949+
const professionalId = new mongoose.Types.ObjectId();
13950+
await Test.insertMany([{ professionalId, name: 'test' }]);
13951+
13952+
const doc = await Test.findOne({ professionalId }).lean().orFail();
13953+
assert.ok(doc.professionalId instanceof mongoose.Types.ObjectId);
13954+
});
1392913955
});
1393013956

1393113957
describe('Check if instance function that is supplied in schema option is available', function() {

0 commit comments

Comments
 (0)