Skip to content

Commit

Permalink
fix: set flattenObjectIds to false when calling toObject() for intern…
Browse files Browse the repository at this point in the history
…al purposes

Fix #14935
  • Loading branch information
vkarpov15 committed Oct 6, 2024
1 parent e7d7652 commit 47c3b46
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
3 changes: 1 addition & 2 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ const subclassedSymbol = Symbol('mongoose#Model#subclassed');
const { VERSION_INC, VERSION_WHERE, VERSION_ALL } = Document;

const saveToObjectOptions = Object.assign({}, internalToObjectOptions, {
bson: true,
flattenObjectIds: false
bson: true
});

/**
Expand Down
3 changes: 2 additions & 1 deletion lib/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ exports.internalToObjectOptions = {
depopulate: true,
flattenDecimals: false,
useProjection: false,
versionKey: true
versionKey: true,
flattenObjectIds: false
};
26 changes: 26 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13926,6 +13926,32 @@ describe('document', function() {
cur.subdocs[0] = { test: 'updated' };
await savedDoc.save();
});

it('avoids flattening objectids on insertMany (gh-14935)', async function() {
const TestSchema = new Schema(
{
professionalId: {
type: Schema.Types.ObjectId
},
firstName: {
type: String
},
nested: {
test: String
}
},
{
toObject: { flattenObjectIds: true }
}
);
const Test = db.model('Test', TestSchema);

const professionalId = new mongoose.Types.ObjectId();
await Test.insertMany([{ professionalId, name: 'test' }]);

const doc = await Test.findOne({ professionalId }).lean().orFail();
assert.ok(doc.professionalId instanceof mongoose.Types.ObjectId);
});
});

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

0 comments on commit 47c3b46

Please sign in to comment.