Retrieving User Collection from API / MongoDB but exclude Password Field?

Multi tool use
Retrieving User Collection from API / MongoDB but exclude Password Field?
I am constructing an api which retrieves articles. I also have users in my database, and would like to have one endpoint which returns the user. /api/users/:userid
. This returns something along these lines:
/api/users/:userid
{
"articles": , //array w. references to articles the user has written
"_id": "5b1321321bcda0e3364251d7e4a",
"email": "user@email.com",
"password": "$2a$1231241gi14k41k42bk12bh3k127iP/k1LAqwPdbgF/bXXpRia",
"__v": 0
}
-- However, I am not sure whether it's a good idea to return the (encrypted) password in the API. Can I somehow exclude this field, or would you recommend to store emails + user_ids in a separate collection on mongodb, or how are things like this usually handled?
2 Answers
2
you can use Project Fields to Return from Query
to exclude password field from your response.
Project Fields to Return from Query
db.users.find( { email: "user@email.com" }, { password: 0} )
I just looked it up: To exclude is
0
, not a -1
- so that works! Is this solution recommended as well or are there still security concerns involved?– R. Kohlisch
Jul 1 at 12:41
0
-1
yes for excluding any field, correct is
0
instead of -1
– Devratna
Jul 1 at 12:42
0
-1
if it helps you then plz vote up
– Devratna
Jul 1 at 12:54
Alright It is not best practice and advisable to return a user's password
. What I normally do is use the lodash
library for operations like this for example, you can have a utility function that omits the password field before your API returns a response like so
password
lodash
function omitPassword(user) {
return _.omit(user.toObject(), ['password']);
}
basically _.omit
is a method from lodash. I hope this helps what you are looking for.
function omitPassword(user) {
return _.omit(user.toObject(), ['password']);
}
_.omit
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
are you sure this is correct? I just tried it and it gives me email and password only - so it doesn't excludes the password, but everything else it seems?
– R. Kohlisch
Jul 1 at 12:39