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

140
Vistas
Express - Mongoose - How to add user data to POST request when submitting a form?

I'm new to Mongoose and NodeJS and I'm building a ticket management system where logged in users can fill up a form to create a ticket. It has two fields (title and description) but when submitting it, I'd like to also add some user's data to the form data object.

On the front end I'm using React with Formik to handle the form. My user data object is stored in local storage using JWT.

Here are my current models for the ticket and for the user:

//ticket.model.js
module.exports = (mongoose) => {
  const Ticket = mongoose.model(
    'ticket',
    mongoose.Schema(
      {
        title: String,
        description: String,
      },
      { timestamps: true }
    )
  );
  return Ticket;
};

//user.model.js
const User = mongoose.model(
  'User',
  new mongoose.Schema({
    firstName: String,
    lastName: String,
    email: String,
    password: String,
    roles: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Role',
      },
    ],
  })
);
module.exports = User;

Here is the Formik function:

const formik = useFormik({
    initialValues: {
      title: '',
      description: '',
    },
    validationSchema,
    validateOnBlur: false,
    validateOnChange: false,
    onSubmit: (data) => {
      TicketService.create(data).then(() => {
        navigate('/home');
        window.location.reload();
      });
    },
  });

Ideally, when the ticket is being created I'd like to query Mongoose with user's ObjectId to retrieve his firstName and lastName. If it's too complicated I don't mind just adding the user's names to the form data using JSON.parse(localStorage.getItem('user')). Or if you have better practices, please let me know.

Thank you!

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

0

Never mind, my formik object was actually missing the user element (see below).

const formik = useFormik({
  initialValues: {
    title: '',
    description: '',
    authorId: JSON.parse(localStorage.getItem('user')).id,
    authorName: `${JSON.parse(localStorage.getItem('user')).firstName} ${
      JSON.parse(localStorage.getItem('user')).lastName
    }`,
  },
  validationSchema,
  validateOnBlur: false,
  validateOnChange: false,
  onSubmit: (data) => {
    console.log(data);
    TicketService.create(data).then(() => {
      navigate('/home');
      window.location.reload();
    });
  },
});

From there I just updated my model and controller accordingly:

module.exports = (mongoose) => {
  const Ticket = mongoose.model(
    'ticket',
    mongoose.Schema(
      {
        title: String,
        description: String,
        authorId: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User',
        },
        authorName: String,
      },
      { timestamps: true }
    )
  );
  return Ticket;
};
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