Last active
December 11, 2015 23:58
-
-
Save nickpoorman/4680204 to your computer and use it in GitHub Desktop.
Node Mongoose attr_accessible - how I make my sub documents have public attributes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* this method is async */ | |
UserSchema.methods.toPublic = function(done) { | |
if(typeof done !== "function") { | |
return undefined; | |
} | |
// this is a shared object, so beware of concurrency issues | |
var publicObj = { | |
_id: this.id, | |
email: this.email, | |
firstName: this.firstName, | |
lastName: this.lastName, | |
username: this.username | |
}; | |
// add all the functions used to map models here | |
var toMap = []; | |
// map the posts model | |
if(this.profile && this.profile.posts) { | |
toMap.push(function(publicObj, callback) { | |
async.map(this.profile.posts || [], function(post, cb) { | |
post.toPublic(function(err, obj) { | |
if(err) { | |
return cb(err, null) | |
} | |
cb(null, obj); | |
}); | |
}, function(err, posts) { | |
if(err) return callback(err); | |
// add posts to the public object to be returned | |
publicObj.profile = { | |
posts: posts | |
} | |
callback(null, publicObj); | |
}); | |
}.bind(this, publicObj)); | |
} | |
// this will run each of the model map functions in parallel | |
async.parallel(toMap, function(err, results) { | |
if(err) return console.log(err); | |
done(null, publicObj); | |
}); | |
}; // end toPublic method |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment