【发布时间】: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://<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;
}
【问题讨论】:
-
错误说明很清楚:
(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