简体   繁体   English

如何使用 mongoose 更新并检查 email 是否存在

[英]How do I update with mongoose and check if email exists

Seems like I cannot figure it.好像我想不通。

The function must check if the email already exists in the collection. function 必须检查 email 是否已存在于集合中。 If the email exists then the person has already made an appointment.如果 email 存在,则此人已预约。 If the email exists, then an Update on the time must be executed.如果 email 存在,则必须执行时间更新。 And if email does not exists then it must save the req.body as a new document如果 email 不存在,则必须将 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);
                                }
                            })
                        }
                    }
                }); 
        }
    })
});

Even though the email exists in the collection, it keeps on creating a document and not update即使集合中存在 email,它也会继续创建文档而不更新

Change this line of code:更改这行代码:

Appointment.findOne(email)

to:至:

Appointment.findOne({email: email})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM