DEV Community

Pratyush Srivastava
Pratyush Srivastava

Posted on • Edited on

Ways on how you can remove password field from mongodb query result.

Working on my MERN stack project (which I will reveal in the future), I came across an issue that almost everyone faces at least once when dealing with Mongoose and MongoDB queries.

It happens when we query some result from MongoDB, and the result contains sensitive information that we do not want to share with the client.

I searched for solutions and found some simple ways to avoid this:


First way: Using destructuring of the ._doc object from the MongoDB response

if (newUser) {
    const { password: pwd, ...responseData } = newUser._doc; // <--
    res.status(201).json({
        msg: "User created successfully.",
        user: responseData
        // user: newUser
    })
}
Enter fullscreen mode Exit fullscreen mode

Here, by using the ._doc object, you can separate the password from the rest of the data and return only the safe response data, without worrying about sending sensitive data to the client.


Second way: Using the select method to remove the password field

const user = await User.findById(_id).select("-password"); // <--
return res.status(200).json({
    msg: "User found",
    user
})
Enter fullscreen mode Exit fullscreen mode

The select method provided by Mongoose lets you easily remove the password field.

Its best use case is in conjunction with the various find methods provided by Mongoose.


Third way: Using the lean method provided by Mongoose

const user = await User.findOne({ email }).lean(); // <--
if(!user) return res.status(400).json({ err: "User does not exist!" })

delete user.password;

const token = jwt.sign(
    { _id: user._id },
    process.env.JWT_SECRET
);

res.status(200).json({
    msg: "User logged in, successfully",
    token
})
Enter fullscreen mode Exit fullscreen mode

The lean method is new for me, as I had never used it before.

This method converts the object returned by MongoDB queries into a plain JavaScript object.

Keep in mind: it removes all the functions associated with the query object, so be careful when using it.

The benefit is that, once converted to a regular object, you can easily perform operations like deleting the password key, as shown above.


So these are three ways to remove sensitive fields from MongoDB queries.

If this was helpful, give a follow, since I’ll be posting tips like this—and more stuff is coming soon!

Top comments (0)