Reputation: 1317
In my node.js express application I am retrieving a user from my database
const newUser = await User.create({
username,
password,
email,
avatar,
})
but before sending the response with the user object I want to remove the password.
delete newUser.password;
return res.status(200).json({ token, user: newUser });
but in my response the password is returned.
console.log(JSON.stringify(newUser))
returns:
{"_id":"11111111","username":"dylan","email":"[email protected]","admin":true,"password":"******"}
Upvotes: 0
Views: 215
Reputation: 108
query return value is document not javascript object
toObject
method which converts the mongoose document into a plain JavaScript object.delete
on each property you wantalso with mongoose
it can done more properly and automatically
User.methods.toJSON = function () {
const user = this;
const userObj = user.toObject();
delete userObj.password;
return userObj;
};
every time you send this document as response it convert to JSON and every time that JSON.strigify()
is call on a document it call this toJSON()
method
Upvotes: 4