'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!
Solution 1:[1]
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;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tyler2P |
