I'm wondering how to use the .create()
method with a protected route while using deconstructed JavaScript. Without the protected route, I can deconstruct my schema and use req.body
in .create(...)
like below.
const { title, year, producer, director, licenseStart, licenseEnd, platform, requestorName, requestorEmail, requestorDepartment, price, notes } = req.body
Without deconstructing it, I can make it work in .create()
and .save()
but it is 14-15 lines and does not feel like best practice. See below.
const newPurchase = new Purchase({
user: req.user.id,
title: req.body.title,
year: req.body.year,
producer: req.body.producer,
director: req.body.director,
licenseStart: req.body.licenseStart,
licenseEnd: req.body.licenseEnd,
platform: req.body.platform,
requestorName: req.body.requestorName,
requestorEmail: req.body.requestorEmail,
requestorDepartment: req.body.requestorDepartment,
price: req.body.price,
notes: req.body.notes
});
const savedPurchase = await newPurchase.save();
My problem is...how the heck do you deconstruct both user:req.user.id
and the req.body
properties and use them both in the same .create()
method? .create(req.body)
works, but .create(req.body, { user: req.user.id })
does not. I've tried several other variations as well.
CodePudding user response:
Hi I'm not really sure what you mean by making this work:
.create(req.body, { user: req.user.id })
But I usually use the .create() like this:
async function createUser(req, res) {
const {
firstName,
lastName,
gender,
profilePicture,
email,
password
} =
req.body;
try {
const schema = object().keys({
firstName: string().required(),
lastName: string().required(),
gender: string().optional(),
profilePicture: string().optional(),
email: string().required(),
password: string().required(),
});
const validation = validate(req.body, schema);
if (validation.error !== null)
throw new Error(validation.error.details[0].message);
const user = await User.findOne({
email
});
if (user) {
res.status(400).json({
success: false,
message: "Email Already Exist"
});
return;
}
const data = await User.create({
firstName,
lastName,
gender,
profilePicture,
email,
password,
lastLogin: new Date(),
});
const newUser = await User.findById(data._id);
res.json({
success: true,
message: "user details",
data: newUser,
});
} catch (error) {
console.error(error);
res.json({
success: false,
message: "user not found",
error
});
}
}
Hopes this helps
CodePudding user response:
I figured out the answer to my own question. I thought I had tried this before but it worked this time.
const setPurchases = asyncHandler(async (req, res) => {
const {title, year, producer, director, licenseStart, licenseEnd, platform, requestorName, requestorEmail, requestorDepartment, price, notes} = req.body
if (!title || !year || !producer || !director || !licenseStart || !licenseEnd|| !platform || !requestorName || !requestorEmail || !requestorDepartment || !price || !notes){
res.status(400)
throw new Error('Please fill in all the fields')
}
**const purchase = await Purchase.create(Object.assign({user:req.user.id}, req.body));**
This allowed me to deconstruct the Purchase Schema object and use both it and the user object in the create() method. This is a lot cleaner than the code below and having user: req.user.id plus 12 req.body objects like title: req.body.title, name: req.body.name, year: year.req.body.year, producer... etc in the .create() method. The code above is much cleaner than below and what I've been looking for. Hopefully it will help anyone else dealing with the same issue or a novice like me. Also keep in mind it works with .save() as well, albeit a bit different as shown in my original question.
const setPurchases = asyncHandler(async (req, res) => {
if (!title || !year || !producer || !director || !licenseStart || !licenseEnd|| !platform || !requestorName || !requestorEmail || !requestorDepartment || !price || !notes){
res.status(400)
throw new Error('Please fill in all the fields')
}
const purchase = await Purchase.create({
title: req.body.title,
year: req.body.year,
producer: req.body.producer,
director: req.body.director,
licenseStart: req.body.licenseStart,
licenseEnd: req.body.licenseEnd,
platform: req.body.platform,
requestorName: req.body.requestorName,
requestorEmail: req.body.requestorEmail,
requestorDepartment: req.body.requestorDepartment,
price: req.body.price,
notes: req.body.notes})