如何修复此节点控制器功能并从2种不同模型发送数据?

时间:2019-10-07 09:43:52

标签: node.js mongodb express mongoose nodemailer

有2种型号可以预订和列出。关键是要创建预订,我们还需要使用列表详细信息,并在将详细信息保存到数据库之后通过Nodemailer发送所有详细信息。这是代码:

列表模型:

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' }]
});
...

预订模式:

const bookingSchema = new Schema({
customerEmail: {
type: String,
match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/]
},
  days: Number,
  listing: { type: Schema.Types.ObjectId, ref: 'Listing'},

控制器:

    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."
        });
    }
    };

控制器从列表模型和预订模型中获取包含字段的数据,然后它将数据保存在数据库中以用于列表模型和预订模型,然后通过电子邮件发送数据。该控制器如何固定?

0 个答案:

没有答案