如何使用 mongoose 进行更新并检查电子邮件是否存在

问题描述

好像我想不通。

函数必须检查该电子邮件是否已存在于集合中。如果电子邮件存在,则该人已经预约了。如果电子邮件存在,则必须执行时间上的更新。如果电子邮件不存在,则必须将 req.body 保存为新文档

router.put('/appointment',(req,res) => {
    let appointmentData = req.body;
    const email = appointmentData.email;
    const time = appointmentData.time;
    appointmentData.full_date = new Date();
    Appointment.findOne(email).exec((err,booking)=> {
        if(booking){
            Appointment.findOneAndUpdate(email,{time: time},{
                new: true,upsert: true
                
            });
            console.log("Item exists");
        }
        else{
            let appointment = new Appointment(appointmentData);
                Tenant.findById({ _id: appointmentData.email /*_id:appointmentData.day*/ },(err,tanent) => {
                    if (err) {
                        console.error("appointment booking error :",err);
                    } else {
                        if (!tanent) {
                            res.status(400).send('Error Finding tenant');
                        } else {
                            appointment.save((err,appointmentBooked) => {
                                if (err) {
                                    console.log("Error booking in cleaning appointment" + err);
                                } else {
                                    res.status(200).send(appointmentBooked);
                                }
                            })
                        }
                    }
                }); 
        }
    })
});

即使电子邮件存在于集合中,它也会继续创建文档而不更新

解决方法

更改这行代码:

Appointment.findOne(email)

到:

Appointment.findOne({email: email})