MongoDB Atlas/Cloud Update and Delete not working

885 Views Asked by At

I have a problem when I try to update or delete data from my MongoDB Atlas database.

The thing is, it looks like the "updateOne" and "deleteOne" methods are being called but not in the right way.

Whenever I try to retrieve the operation the result is the following:

{
    "result": {
        "n": 0,
        "nModified": 0,
    [...]
    "ok": 1,
    [...]
    "modifiedCount": 0,
    "upsertedId": null,
    "upsertedCount": 0,
    "matchedCount": 0,
    "n": 0,
    "nModified": 0,
    [...]
}

These are my methods:

const ObjectID = require('mongodb');

[...]

// Deletes an specific object [NOT WORKING]
router.delete('/:dataID', async (req, res) => {
    // http://localhost:3000/data/<dataID>
    try {
        const removedObject = await collectionDatos.deleteOne({ "_id" : ObjectID("\"" + req.params.dataID + "\"") });
        res.json(removedObject );
    } catch (e) {
        console.log(e);
        res.json({message: e});
    }
});

// Updates an specific object [NOT WORKING]
router.patch('/:dataID', async (req, res) => {
    // http://localhost:3000/data/<dataID>
    try {
        const updatedObject = await collectionDatos.updateOne({_id: req.params.dataID}, { $set: {
                name: req.body.name,
                surname: req.body.surname,
                born_date: req.body.born_date,
                email: req.body.email
            }});
        res.json(updatedObject);
    } catch (e) {
        console.log(e);
        res.json({message: e});
    }
});

Specifically, when I call the removeOne method, it throws me this error trace:

(node:12222) UnhandledPromiseRejectionWarning: MongoParseError: Invalid connection string
    at parseConnectionString

(node:12222) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

(node:12222) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I am sure the error is in const removedObject = await collectionDatos.deleteOne({ "_id" : ObjectID("\"" + req.params.dataID + "\"") }); and const updatedObject = await collectionDatos.updateOne({_id: req.params.dataID}, { $set: { [...] } but I'm only doing what the documentation says :(

[deleteOne: https://docs.mongodb.com/manual/reference/method/db.collection.deleteOne/] [updateOne: https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/]

What do i have to change to make it work? The truth is that there are not many resources / tutorials out there other than documentation and it is making my life bitter. Thank you in advance!

Edit:

This is my connection String: mongodb+srv://<USER>:<PASS>@cluster0.znqxh.mongodb.net/<DATABASE_NAME>?retryWrites=true&w=majority

This is the way I make the connection:

function connectToDatabse() {
    console.log("Connecting to the DB...");
    if (!connected) {
        const MongoClient = require('mongodb').MongoClient;
        const uri = process.env.DB_CONNECTION;
        client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
        client.connect(async err => {
            if (await err) {
                console.log("Error connecting to MongoDB:\n\t" + err.toString());
                await console.log('Disconnecting from the DB...');
                await client.close();
                await console.log('\tDisconnected from the DB!');
                await process.exit();
            } else {
                console.log("\tConnected to the DB!");
                collectionData = client.db("dataBase").collection("data");
            }
        });
    }
    connected = true;
}
1

There are 1 best solutions below

2
On BEST ANSWER

On the first line you're pulling the entire lib instead of ObjectId.

const ObjectID = require('mongodb');

Change it to:

const { ObjectId } = require('mongodb');

Also, don't forget to update the places where you're using ObjectID to ObjectId.