There are 2 models booking and listing. The point is that for creating a booking we need to use listing details too and send all the details through the Nodemailer after the saving details in DB. here is the code:
Listing model:
const listingSchema = new Schema({
bbusinessEmail: {
type: String,
},
title: { type: String, required: true, max: [128, 'Too long, max is 128 characters']},
city: { type: String, required: true, lowercase: true },
street: { type: String, required: true, min: [4, 'Too short, min is 4 characters']},
bookings: [{ type: Schema.Types.ObjectId, ref: 'Booking' }]
});
...
Booking model:
const bookingSchema = new Schema({
customerEmail: {
type: String,
match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/]
},
days: Number,
listing: { type: Schema.Types.ObjectId, ref: 'Listing'},
Controller:
exports.bookListing = async (req, res) => {
if(!req.body.content) {
return res.status(400).send({
message: "Fields can not be empty"
});
}
const smtpTransport = nodemailer.createTransport({
service: 'Gmail',
port: 465,
auth: {
user: 'email',
pass: 'password'
}
});
const { customerEmail, businessEmail, customerPhone, startAt, listing,
totalPrice, days } = req.body;
const booking = new Booking({
customerEmail,
customerPhone,
startAt,
totalPrice,
days
});
let foundListing = await Listing.findById(listing._id).populate('bookings')
if (err) {
return res.status(422).send({message: "Error happened"});
}
booking.listing = foundListing;
foundListing.bookings.push(booking);
try {
let data = await booking.save(), foundListing.save();
var mailOptions = {
from: data.customerEmail,
to: data.businessEmail,
subject: 'Listing Request',
html: `<p>${data.startAt}</p>
<p>${data.totalPrice}</p>
<p>${data.customerPhone}</p>
<p>${data.days}</p>`
};
await smtpTransport.sendMail(mailOptions);
smtpTransport.close();
res.send(data);
} catch(err) {
res.status(500).send({
essage: err.message || "Some error occurred while creating the listing."
});
}
};
The controller gets data that includes fields from both Listing and booking models then it should save data inside the DB for both Listing and booking and then send the data through the email. How can this controller be fixed?