From 5ba8628ea18ffc90d39f0b8bb1241bebdb6cf675 Mon Sep 17 00:00:00 2001 From: Samkit Jain Date: Sat, 5 Dec 2020 21:49:02 +0530 Subject: [PATCH] delete private nested objects --- src/models/plugins/toJSON.plugin.js | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/models/plugins/toJSON.plugin.js b/src/models/plugins/toJSON.plugin.js index bb7abda9..12af055f 100644 --- a/src/models/plugins/toJSON.plugin.js +++ b/src/models/plugins/toJSON.plugin.js @@ -5,6 +5,16 @@ * - removes __v, createdAt, updatedAt, and any path that has private: true * - replaces _id with id */ + + +const deleteAtPath = (obj, path, index) => { + if (index === path.length - 1) { + delete obj[path[index]]; + return; + } + deleteAtPath(obj[path[index]], path, index + 1); +}; + const toJSON = (schema) => { let transform; if (schema.options.toJSON && schema.options.toJSON.transform) { @@ -15,7 +25,7 @@ const toJSON = (schema) => { transform(doc, ret, options) { Object.keys(schema.paths).forEach((path) => { if (schema.paths[path].options && schema.paths[path].options.private) { - delete ret[path]; + deleteAtPath(ret, path.split('.'), 0); } });