MongoDB Atlas/Cloud 更新和删除不起作用
MongoDB Atlas/Cloud Update and Delete not working
当我尝试更新或删除我的 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;
}
在第一行,您将拉取整个库而不是 ObjectId。
const ObjectID = require('mongodb');
改为:
const { ObjectId } = require('mongodb');
此外,不要忘记将您使用 ObjectID 的地方更新为 ObjectId。
当我尝试更新或删除我的 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;
}
在第一行,您将拉取整个库而不是 ObjectId。
const ObjectID = require('mongodb');
改为:
const { ObjectId } = require('mongodb');
此外,不要忘记将您使用 ObjectID 的地方更新为 ObjectId。