Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

396
Vistas
How to remove a specific key from JSON response coming from MongoDB in ExpressJS

I'm creating a simple application using MEAN stack. My code is working fine but i want to remove one key from the response. Please look at my ocde.

models/user.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const userSchema = new Schema({
    firstName: String,
    lastName: String,
    email: String,
    //password: String, // <--------- commented out
    userid: String,
    skills: []
})

module.exports = mongoose.model('user', userSchema, 'users');

Notice that I've commented out password key. But I guess that's not enough. As I can still see password in response:

Postman screenshot

(Note: Email Id and encrypted Password in this image are absolutely fake and hence there's no security issue)

enter image description here

api.js

const User = require('../models/user');
...
router.get('/users', function (req, res) {
    console.log('Get request for all users');
    User.find({})
        .exec(function (err, user) {
            if (err) {
                console.log("Error retrieving users");
            } else {
                res.json(user);
            }
        });
});

Now tomorrow When I'll be using real email and password, though I'll encrypt the password but still i don't want to show password key whatsoever. It should not be displayed in the network tab of browser also.

Please give me some directions.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can use the mongoose select method to exclude certain fields. https://mongoosejs.com/docs/api.html#query_Query-select

User.find({})
        .select('-password')
        .exec(function (err, user) {
            if (err) {
                console.log("Error retrieving users");
            } else {
                res.json(user);
            }
        });

over 4 years ago · Santiago Trujillo Denunciar

0

You can try this :

const User = require('../models/user');
...
router.get('/users', function (req, res) {
    console.log('Get request for all users');
    const user = User.find({} , {password:0});

    return res.json({ user: user });
});
over 4 years ago · Santiago Trujillo Denunciar

0

If you just do not want to show the password while outputting the data then you just need to do this in your schema:

const MongooseSchema = new mongoose.Schema({
  firstName: {
    type: String,
    required: [true, 'Please enter a first name!'],
  },
  lastName: {
    type: String,
    required: [true, 'Please enter a last name!'],
  },
  email: {
    type: String,
    unique: true,
    required: [true, 'Please enter an email address!'],
    match: [
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      'Please enter a valid email address',
    ],
  },
  password: {
    type: String,
    required: [true, 'Please enter a password'],
    select: false,
  },
  // userid: String, Id for user will be created by mongodb automatically
  skills: {
    type: Array,
    required: [true, 'Please enter skills!'],
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model('User', MongooseSchema);

Now when you will find users or a user, a password or passwords will not be returned in the response. I improved your schema too.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda