using _.omit on mongoose User in node.js -
i have mongoose user schema built this:
var userschema = new schema({ username: { type: string, required: true, index: { unique: true } }, password: { type: string, required: true }, salt: { type: string, required: true} });
i want able send user object client side of application don't want sned password or salt fields.
so added following code user model module
u
serschema.methods.forclientside = function() { console.log('in userschema.methods.forclientside'); console.log(this); //var userforclientside=_.omit(this,'passsword','salt'); var userforclientside={_id:this._id, username:this.username }; console.log(userforclientside); return userforclientside; }
i have required
underscore module (its installed locally via dependency in package.js).
not commented out line - expecting omit password , salt fields of user object did not :( logged object had full set of properties.
when replaced used var userforclientside={_id:this._id, username:this.username };
gets results want but:
1) want know why _.omit
not work. 2) don't current workaround because selects properties instead of omitting ones don't if add new propertes scema have add them here well.
this first attempt @ writing using node.js/express/mongodb/mongoose etc. possible hat missing other better solution issue (possibly feature of mongoose ) feel free educate me of right way things this.
so want know both right way , why did way not work.
thanks
1) want know why _.omit not work.
mongoose uses defineproperty
, heavy metaprogramming. if want use underscore, first call user.tojson()
plain old javascript object work better underscore without metaprogramming fanciness, functions, etc.
a better solution use mongo/mongoose's fields
object , pass string "-password -salt"
, therefore omit getting these mongo @ all.
another approach use mongoose transform (search "tranform" on page). use case exact use case documentation uses example.
you can make mongoose queries "lean" calling .lean()
on query, in case plain javascript objects instead of mongoose model instances.
however, after trying each of these things, i'm coming opinion there should separate collection account
has login details , user
collection, make leaking hashes extremely unlikely accident, of above work.
Comments
Post a Comment