Esto debería ser lo suficientemente flexible para la mayoría de las necesidades:
function dotNotate(obj,target,prefix) {
target = target || {},
prefix = prefix || "";
Object.keys(obj).forEach(function(key) {
if ( typeof(obj[key]) === "object" && obj[key] !== null ) {
dotNotate(obj[key],target,prefix + key + ".");
} else {
return target[prefix + key] = obj[key];
}
});
return target;
}
Ejecutar en su excludesFields
variable así:
dotNotate(excludeFields);
Devuelve la estructura actual:
{ "Contact.Address" : 0, "Contact.Phone" : 0 }
Así que incluso puedes hacer, en línea:
things.findOne({}, {fields: dotNotate(excludeFields) })
O proporcione como proyección:
var projection = { "fields": {} };
dotNotate(excludeFields,projection.fields);
things.findOne({}, projection);
Funciona bien en todas las profundidades e incluso con arreglos de manera esencial, a menos que necesite operadores como $push
.