Une fonction d'aide récursive couvre la plupart des cas :
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;
}
Exécutez-la sur votre objet excludesFields :
dotNotate(excludeFields);
Vous récupérez la structure aplatie :
{ "Contact.Address" : 0, "Contact.Phone" : 0 }
L'utiliser en ligne
things.findOne({}, {fields: dotNotate(excludeFields) })
Ou construisez d'abord un objet de projection :
var projection = { "fields": {} };
dotNotate(excludeFields,projection.fields);
things.findOne({}, projection);
La fonction s'exécute récursivement à n'importe quelle profondeur et tolère raisonnablement les tableaux — sauf dans les cas où vous avez besoin d'opérateurs de tableau comme $push.