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

159
Visualizações
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!

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

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;
};
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