Skip to content

Commit

Permalink
Merge pull request #193 from Springworks/fix/id-removal
Browse files Browse the repository at this point in the history
fix: remove id property deep
  • Loading branch information
petrenkotino authored Apr 3, 2017
2 parents 61c012b + e7b2924 commit 272c8ad
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/mongoose-cleaner.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -30,8 +43,9 @@ const api = {
}

delete lean.__v;
delete lean.id;
return convertObjectIds(lean);
lean = convertObjectIds(lean);
removeIds(lean);
return lean;
},

};
Expand Down
39 changes: 39 additions & 0 deletions test/unit/mongoose-cleaner-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand All @@ -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();

Expand Down Expand Up @@ -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', () => {
Expand Down

0 comments on commit 272c8ad

Please sign in to comment.