node.jsmongodbmongoosemongodb-query

MongoDB .deleteOne not working in Node.js


So, i'm trying to delete a document when a button is pressed. The button code looks like this:

<form action="/patients/delete?_method=DELETE" method="POST">
    <input type="hidden" id="patientID" name="patientID" value=' _id: <%= patient._id%>'>
    <button type="submit" class="btn btn-primary">Delete this patient from the Database</button>
</form>

I've set up a route which looks like this:

router.delete('/delete', AuthControl.checkLoggedIn, patientsControl.patientDelete);

Which is calling this function in patientsControl:

    patientDelete = async (req, res) => {
    let DeleteParam = req.body.patientID;
    console.log(DeleteParam);
    let DeleteConfirm = await this.patientsModel.DeletePatient(DeleteParam);
    if (DeleteConfirm) {
        res.render('patients');
    } else {
        console.log("Error happening somewhere");
        }
    }

which is calling this function in the patientsModel:

async DeletePatient(DeleteParam) {
    return mongoose.connection.db.collection("PatientsDB").
    deleteOne({ _id : DeleteParam);
}

//EDIT: quickly fixed the above code, wasn't what I was running Which is returning true, as I'm not logging an error in patientDelete above.

the console.log(DeleteParam); is returning the id for the document i'm trying to delete, like this: 5f22dc43b1e72e9769263810

and the document im trying to delete looks like this:

_id : 5f22dc43b1e72e9769263810
fName : "s"
lName : "s"
diseases : "s"
prescriptions : []
inhousedoctor : "s"

What confuses me is, that if i set the button value to <%= patient.fName %> instead, it deletes perfectly. Can anyone please tell me what i'm doing wrong?

Edit: Ofc I mean that it works when i use fName instead like this:

        return mongoose.connection.db.collection("PatientsDB").
        deleteOne( {fName : DeleteParam});
    }```

Solution

  • The _id of the document is of type ObjectId but you are searching for a string, so no documents match.

    If you use a Mongoose model, the type is converted automatically. But here you are not actually using Mongoose other than as a way to get the underlying MongoDB connection (mongoose.connection). So you are then working with pure MongoDB which does not do the conversion for you.

    So you can either use the corresponding Mongoose model and write e.g. Patient.deleteOne({ _id: DeleteParam }) or just Patient.findByIdAndDelete(DeleteParam), or you can continue using MongoDB directly but explicitly convert the value to an ObjectId, using { _id: mongoose.Types.ObjectId(DeleteParam) }.