This should be flexible enough for most needs:
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;
}
Run on your excludesFields
variable like so:
dotNotate(excludeFields);
It returns the current structure:
{ "Contact.Address" : 0, "Contact.Phone" : 0 }
So you can even do, inline:
things.findOne({}, {fields: dotNotate(excludeFields) })
Or provide as a projection:
var projection = { "fields": {} };
dotNotate(excludeFields,projection.fields);
things.findOne({}, projection);
Works nicely at all depths and even with arrays in an essential way, unless you need operators like $push
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…