【问题标题】:MongoDB Atlas/Cloud Update and Delete not workingMongoDB Atlas/云更新和删除不起作用
【发布时间】:2021-06-12 23:56:43
【问题描述】:

当我尝试从我的 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://&lt;USER&gt;:&lt;PASS&gt;@cluster0.znqxh.mongodb.net/&lt;DATABASE_NAME&gt;?retryWrites=true&amp;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;
}

【问题讨论】:

  • 错误说明很清楚:(node:12222) MongoParseError: Invalid connection string at parseConnectionString。请检查您的连接字符串或将其发布在问题中,以便有人可以验证它。
  • 当然,我已经用信息更新了主帖。
  • 不要创建ObjectId,只传递id。猫鼬自己处理。 ObjectID("\"" + req.params.dataID + "\"" 变为 req.params.dataID

标签: javascript node.js mongodb mongodb-atlas mongodb-cloud


【解决方案1】:

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

const ObjectID = require('mongodb');

改成:

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

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

【讨论】:

  • 非常感谢!这解决了router.delete 方法。我将const removedObject = await collectionData.deleteOne({ "_id" : ObjectID("\"" + req.params.dataID + "\"") }); 更改为const removedObject = await collectionData.deleteOne({ "_id" : ObjectId(req.params.datoID) }); 以使其在收到Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters 错误后工作
  • 另外,将const updatedObject = await collectionDatos.updateOne({_id: req.params.dataID}, { $set: { 更改为const updatedObject = await collectionDatos.updateOne({"_id": : ObjectId(req.params.dataID)}, { $set: { 使router.patch 方法工作。
猜你喜欢
  • 1970-01-01
  • 2019-08-11
  • 2020-07-07
  • 2015-02-02
  • 1970-01-01
  • 1970-01-01
  • 2018-06-06
  • 2012-09-22
  • 2015-03-13
相关资源
最近更新 更多