Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections?

Suppose I have two collections/schemas. One is the Users Schema with username and password fields, then, I have a Blogs Schema that has a reference to the Users Schema in the author field. If I use Mongoose to do something like

Blogs.findOne({...}).populate("user").exec() 

I will have the Blog document and the user populated too, but how do I prevent Mongoose/MongoDB from returning the password field? The password field is hashed but it shouldn't be returned.

I know I can omit the password field and return the rest of the fields in a simple query, but how do I do that with populate. Also, is there any elegant way to do this?

Also, in some situations I do need to get the password field, like when the user wants to login or change the password.

like image 217
Luis Elizondo Avatar asked Aug 23 '12 16:08

Luis Elizondo


People also ask

Can you store passwords in MongoDB?

js, MongoDB, and Mongoose, there will be times where you'll need to handle user passwords. Since it's a big no-no to store passwords as plain-text in your database, how are you supposed to handle and store them? The answer is to create what's called a hash of the password.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.

What does Mongoose findById return?

findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .

What is user _DOC in Mongoose?

_doc exist on the mongoose object. Because mongooseModel. findOne returns the model itself, the model has structure (protected fields). When you try to print the object with console. log it gives you only the data from the database, because console.


2 Answers

You can change the default behavior at the schema definition level using the select attribute of the field:

password: { type: String, select: false } 

Then you can pull it in as needed in find and populate calls via field selection as '+password'. For example:

Users.findOne({_id: id}).select('+password').exec(...); 
like image 95
JohnnyHK Avatar answered Sep 26 '22 23:09

JohnnyHK


.populate('user' , '-password') 

http://mongoosejs.com/docs/populate.html

JohnnyHKs answer using Schema options is probably the way to go here.

Also note that query.exclude() only exists in the 2.x branch.

like image 37
aaronheckmann Avatar answered Sep 26 '22 23:09

aaronheckmann