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

164
Vistas
MongoDB document naming

I have tried so many time different things but unable understand that whenever I am saving data into MongoDB why am I getting the name of that document as below

User.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema({
  email: {
    type: String,
    require: true,
    unique: true,
    lowercase: true,
  },
  username: {
    type: String,
    require: true,
    unique: true,
    maxLength: 7,
  },
  password: {
    type: String,
    require: true,
    minLength: 8,
  },
});

const User = mongoose.model("user", userSchema);

module.exports = User;

When I have saved the data by hitting API through postman and printing the data in console, the data I am receiving is as below:

    email {
        _id: new ObjectId("627a4ae94b8958e3fe968311"),
        email: 'abc@abc.com',
        username: 'fzee07',
        password: 'test1234',
        __v: 0
      }

So my question is this that why this object is getting saved and named as "email".

registerUser.js

const User = require("../../models/User");

const registerUser = async (req, res) => {
  const { email, username, password } = req.body;

  try {
    const e_mail = await User.findOne({});
    console.log("email", e_mail);
    if (e_mail.email === email) {
      res.status(409).json({
        success: false,
        msg: "User already exists",
      });
    } else {
      if (username.length < 8) {
        if (password.length >= 8) {
          const user = User.create({ email, username, password });
          res.status(201).json({
            success: true,
            data: "User Created",
          });
        } else {
          res.status(401).json({
            success: false,
            data: "Password muste be minimum 8 characters",
          });
        }
      } else {
        res.status(401).json({
          success: false,
          data: "Username must be less than 8 characters",
        });
      }
    }
  } catch (err) {
    console.log(err);
  }
};

module.exports = registerUser;

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I understand the problem now. Sorry about the confusion, I misread the second part of your question. The reason you're getting this in console:

email {
    _id: new ObjectId("627a4ae94b8958e3fe968311"),
    email: 'abc@abc.com',
    username: 'fzee07',
    password: 'test1234',
    __v: 0
  }

Is because you are console logging the string "email", then your user object from the database, which you have confusingly named e_mail.

Change the log message to look like this, and you're good:

console.log("user", e_mail);

In fact, your code needs some severe refactoring. Right now, it's not very readable. Here's an improvement:

const User = require('../../models/User');

const registerUser = async (req, res) => {
    const { email, username, password } = req.body;

    try {
        // Find a user with that email
        const user = await User.findOne({ email });
        console.log('user', user);

        // if it exists, return
        if (user) {
            res.status(409).json({
                success: false,
                message: 'User already exists',
            });
            return;
        }

        // Validate the username and password
        // If validates, create the user
        if (username.length < 8 && password.length >= 8) {
            const newUser = User.create({ email, username, password });

            res.status(201).json({
                success: true,
                message: 'User created',
                data: newUser,
            });
            return;
        }

        // If all else fails, return 401
        res.status(401).json({
            success: false,
            message: 'Username must be less than 8 characters & password must be at least 8 characters long',
        });
    } catch (err) {
        res.status(500).json({
            success: false,
            message: 'Server error',
        });
    }
};

module.exports = registerUser;

I changed all the places where you had the key of data to have the key of message, as messages were the values.

Once again though, I really recommend doing the validation in Mongoose middleware/hooks instead of right within the route. Will save you headaches as your application grows.

about 4 years ago · Juan Pablo Isaza 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