From e7b2924d9d95ee5b9182772f3d26a737a50e49f0 Mon Sep 17 00:00:00 2001 From: Christian Jacobsen Date: Mon, 3 Apr 2017 16:54:28 +0200 Subject: [PATCH] fix: remove id property deep --- src/mongoose-cleaner.js | 18 ++++++++++++-- test/unit/mongoose-cleaner-test.js | 39 ++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/src/mongoose-cleaner.js b/src/mongoose-cleaner.js index 7f60aa8..acde707 100644 --- a/src/mongoose-cleaner.js +++ b/src/mongoose-cleaner.js @@ -13,6 +13,19 @@ function convertObjectIds(obj) { }); } +function removeIds(obj) { + for (const prop in obj) { + if (obj.hasOwnProperty(prop)) { + if (prop === 'id') { + delete obj[prop]; + } + else if (typeof obj[prop] === 'object') { + removeIds(obj[prop]); + } + } + } +} + const api = { cleanMongooseDocument(mongoose_doc) { @@ -30,8 +43,9 @@ const api = { } delete lean.__v; - delete lean.id; - return convertObjectIds(lean); + lean = convertObjectIds(lean); + removeIds(lean); + return lean; }, }; diff --git a/test/unit/mongoose-cleaner-test.js b/test/unit/mongoose-cleaner-test.js index bc9602f..ab7a85a 100644 --- a/test/unit/mongoose-cleaner-test.js +++ b/test/unit/mongoose-cleaner-test.js @@ -7,6 +7,11 @@ const ObjectId = mongoose.Schema.Types.ObjectId; const MockSchema = new mongoose.Schema({ foo: { type: String, required: false }, other_id: { type: ObjectId, required: false }, + nested: [ + { + nested_foo: { type: String, required: false }, + }, + ], }); MockSchema.path('foo').get(value => { @@ -19,6 +24,17 @@ function createMongooseDocument(params) { return new MongooseCleanerModel(params); } +function assertNoIdProperties(obj) { + for (const prop in obj) { + if (obj.hasOwnProperty(prop)) { + prop.should.not.equal('id'); + if (typeof obj[prop] === 'object') { + assertNoIdProperties(obj[prop]); + } + } + } +} + describe('test/unit/mongoose-cleaner-test.js', () => { const sinon_sandbox = autorestoredSandbox(); @@ -72,6 +88,29 @@ describe('test/unit/mongoose-cleaner-test.js', () => { }); + describe('with a DB document having a nested array of documents', () => { + let document; + + beforeEach(() => { + document = createMongooseDocument({ + nested: [ + { + nested_foo: 'hello', + }, + { + nested_foo: 'bar', + }, + ], + }); + }); + + it('should not have `id` anywhere on the document', () => { + const cleaned = cleaner.cleanMongooseDocument(document); + assertNoIdProperties(cleaned); + }); + + }); + describe('when DB document omitted', () => { it('should return null, but not fail', () => {