MongoDB
 SQL >> Database >  >> NoSQL >> MongoDB

Appiattire un oggetto JSON in notazione a punto con JavaScript

Un helper ricorsivo copre la maggior parte dei casi:

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; } 

Eseguilo sul tuo oggetto excludesFields:

dotNotate(excludeFields); 

Ottieni indietro la struttura appiattita:

{ "Contact.Address" : 0, "Contact.Phone" : 0 } 

Usarlo inline

things.findOne({}, {fields: dotNotate(excludeFields) }) 

Oppure costruisci prima un oggetto di proiezione:

var projection = { "fields": {} }; dotNotate(excludeFields,projection.fields); things.findOne({}, projection); 

Ricorre a qualsiasi profondità e gestisce gli array in modo ragionevole, con l'eccezione dei casi in cui servono operatori sugli array come $push.