Gerald Muller
Gerald Muller

Reputation: 23

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. If the email exists then the person has already made an appointment. If the email exists, then an Update on the time must be executed. And if email does not exists then it must save the req.body as a new document

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

Upvotes: 0

Views: 450

Answers (1)

Hassan Mehdi
Hassan Mehdi

Reputation: 63

Change this line of code:

Appointment.findOne(email)

to:

Appointment.findOne({email: email})

Upvotes: 1

Related Questions