Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
how to hide my client's password in API response

I am just a beginner at Javascript & MERN. I am trying to create a small social media app, and in my sign up api, I gave a response of the user's info. I couldn't segregate and hide the password.

here is the code

userRouter.post("/signUp", async (req, res) => {
    
    const {name, userName, email, password} = req.body

    const existingUser = await userSchema.findOne({email: email})
    const SameUserName = await userSchema.findOne({userName: userName})
    if (existingUser) {
        return res.status(406).send({
            message: `sorry, an account with email: ${email} has already been created.`
        })
    } else if (SameUserName) {
        return res.status(406).send({
            message: `sorry, user name taken. Try another one...`
        })
    }

    const newUser = new userSchema({
        name,
        userName,
        email,
        password
    })
    console.log(newUser)

    try {
        await newUser.save()
        res.status(201).send({
            message: `Account successfully created!`,
            user: newUser
        })
    } catch (err) {
        res.send({
            message:`Something went wrong`,
        })
    }
})

So, how can I send the user info without the password?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You'll want to implement the toJSON and transform methods on your schema. This will allow you to 'intercept' schema objects as they are created, and as they are serialized and sent to the client.

Here's an example:

Schema:

import { Schema, model } from 'mongoose';

const schema = new Schema(
    {
        name: {
            required: true,
            type: String
        },
        userName: {
            required: true,
            type: String
        },
        email: {
            required: true,
            type: String
        },
        password: {
            required: true,
            type: String
        }
    },
    {
        // here, we implement the `toJSON` method to serialize the user object sans password, __v;
        // we'll also convert the mongo-specific `_id` property to a db-agnostic format
        toJSON: {
            transform(_, ret) {
                ret.id = ret._id;

                delete ret.password;
                delete ret._id;
                delete ret.__v;
            }
        }
    }
);

// this is our user schema, used to initialize new user objects before we persist them in the db
const User = model('User', schema);

userRouter.post('/signUp', async (req, res) => {
    // grab the inputs - we do *not* at this time know whether any of these are valid - they must be validated
    const { name, userName, email, password } = req.body;

    // validate the email format, performing checks for any requirements you wish to enforce
    if (!email) {
        // error response
    }

    // now, we check if the email is already in-use
    const existingUser = await User.findOne({ email });
    if (existingUser) {
        return res.status(400).send({
            message: `sorry, an account with email: ${email} has already been created.`
        });
    }

    // validate userName format here
    if (!userName) {
        // error response
    }

    // notice we don't bother making this query until `existingUser` check has passed
    // this way we don't incur needless computation
    const sameUserName = await User.findOne({ userName });
    if (sameUserName) {
        return res.status(400).send({
            message: `sorry, user name taken. Try another one...`
        });
    }

    // validate name and password and handle accordingly here
    if (!name || ...) {
        // error response
    }

    // assuming all is well, we create a new user with the schema
    // think of the schema as a template
    const newUser = new User({ name, userName, email, password });

    // save the new user
    await newUser.save().catch((ex) => {
        // error response
    });

    res.status(201).send({
        message: `Account successfully created!`,
        user: newUser
    });
});

You might also look into express-validator, a middleware that handles much of the request body validation for you.

about 4 years ago · Juan Pablo Isaza Relatório

0

Following up on the comment I left below, here is what you can do.

Refactoring of your code is must thou.

try {
 const userSaved = await newUser.save();
 delete userSaved.password // assuming this is the property name
 return res.status(201).send({ message: 'Account created successfully', user: userSaved })
}

you could also just:

try {
 const userSaved = await newUser.save();
 delete userSaved.password // assuming this is the property name
 return userSaved;
}

In this case you handle the message and everything on the front-end.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda