1

当我尝试从 MongoDB Atlas 数据库中更新或删除数据时遇到问题。

问题是,看起来正在调用“updateOne”和“deleteOne”方法,但方法不正确。

每当我尝试检索操作时,结果如下:

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

这些是我的方法:

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});
    }
});

具体来说,当我调用 removeOne 方法时,它会抛出这个错误跟踪:

(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.

我确定错误就在const removedObject = await collectionDatos.deleteOne({ "_id" : ObjectID("\"" + req.params.dataID + "\"") });其中,const updatedObject = await collectionDatos.updateOne({_id: req.params.dataID}, { $set: { [...] }但我只是按照文档中的说明进行操作:(

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

我必须改变什么才能让它工作?事实是,除了文档之外,没有多少资源/教程,这让我的生活变得痛苦。先感谢您!

编辑:

这是我的连接字符串:mongodb+srv://<USER>:<PASS>@cluster0.znqxh.mongodb.net/<DATABASE_NAME>?retryWrites=true&w=majority

这是我建立连接的方式:

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;
}
4

1 回答 1

2

在第一行,您将提取整个库而不是 ObjectId。

const ObjectID = require('mongodb');

将其更改为:

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

另外,不要忘记将使用 ObjectID 的地方更新为 ObjectId。

于 2021-06-12T15:56:43.573 回答