baseModel: delete properties instead of setting them to undefined, transform toJSON only not toObject

This commit is contained in:
Matteo Pagliazzi
2015-11-25 15:19:21 +01:00
parent 77d25ddc32
commit 94fc1c9bef
3 changed files with 10 additions and 9 deletions

View File

@@ -65,6 +65,7 @@
"newrelic": "~1.23.0",
"nib": "~1.0.1",
"nodemailer": "^1.9.0",
"object-path": "^0.9.2",
"pageres": "^1.0.1",
"passport": "~0.2.1",
"passport-facebook": "2.0.0",

View File

@@ -39,7 +39,7 @@ describe('Base model plugin', () => {
let sanitized = schema.statics.sanitize({ok: true, noUpdateForMe: true});
expect(sanitized).to.have.property('ok');
expect(sanitized).to.have.property('noUpdateForMe');
expect(sanitized).not.to.have.property('noUpdateForMe');
expect(sanitized.noUpdateForMe).to.equal(undefined);
});
@@ -48,12 +48,12 @@ describe('Base model plugin', () => {
private: ['amPrivate']
});
expect(schema.options.toObject.transform).to.exist;
expect(schema.options.toJSON.transform).to.exist;
let objToTransform = {ok: true, amPrivate: true};
let privatized = schema.options.toObject.transform({}, objToTransform);
let privatized = schema.options.toJSON.transform({}, objToTransform);
expect(objToTransform).to.have.property('ok');
expect(objToTransform).to.have.property('amPrivate');
expect(objToTransform).not.to.have.property('amPrivate');
expect(objToTransform.amPrivate).to.equal(undefined);
});
});

View File

@@ -1,6 +1,6 @@
import _ from 'lodash';
import { uuid } from '../../../../common';
import validator from 'validator';
import objectPath from 'object-path'; // TODO use lodash's unset once v4 is out
export default function baseModel (schema, options = {}) {
schema.add({
@@ -37,17 +37,17 @@ export default function baseModel (schema, options = {}) {
if (Array.isArray(options.noSet)) noSetFields.push(...options.noSet);
schema.statics.sanitize = function sanitize (objToSanitize = {}) {
noSetFields.forEach((fieldPath) => {
_.set(objToSanitize, fieldPath, undefined); // TODO decide wheter to use delete here
objectPath.del(objToSanitize, fieldPath);
});
return objToSanitize;
};
if (!schema.options.toJSON) schema.options.toJSON = {};
if (Array.isArray(options.private)) privateFields.push(...options.private);
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function transformToObject (doc, plainObj) {
schema.options.toJSON.transform = function transformToObject (doc, plainObj) {
privateFields.forEach((fieldPath) => {
_.set(plainObj, fieldPath, undefined); // TODO decide wheter to use delete here
objectPath.del(plainObj, fieldPath);
});
};
}