英文:
I can't delete a data from mongoDb ObjectId class constructor error
问题
以下是您提供的代码部分的翻译:
const express = require("express");
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
const cors = require("cors");
const app = express();
const port = process.env.PORT || 5000;
//middleware
app.use(cors());
app.use(express.json());
const uri =
"mongodb+srv://<hiddenuser>:<hiddenPass>@cluster0.9mathic.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
});
const run = async () => {
try {
const userCollection = client
.db("simple-node-mongo-server")
.collection("mongo_crud_server");
//将用户数据存储到数据库中
app.post("/users", async (req, res) => {
const user = req.body;
console.log(user);
const result = await userCollection.insertOne(user);
res.send(result);
});
//读取用户数据
app.get("/users", async (req, res) => {
const query = {};
const cursor = userCollection.find(query);
const users = await cursor.toArray();
res.send(users);
});
//删除用户
app.delete("/users/:id", async (req, res) => {
const id = req.params.id;
// console.log('trying to delete', id);
const query = { _id: ObjectId(id) };
console.log(query)
// const result = await userCollection.deleteOne(query);
// console.log(result);
// res.send(result);
});
} finally {
}
};
run().catch(console.dir);
//原始API请求
app.get("/", (req, res) => {
res.send("Hello world");
});
app.listen(port, () => {
console.log(`监听端口5000`);
});
错误信息如下:
C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\index.js:45
const query = { _id: ObjectId(id) };
^
TypeError: 不能在没有'new'的情况下调用类构造函数ObjectId
at C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\index.js:45:28
at Layer.handle [as handle_request] (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\index.js:284:15
at param (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\index.js:365:14)
at param (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\index.js:376:14)
at Function.process_params (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\index.js:421:3)
at next (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\index.js:280:10)
Node.js v18.13.0
[nodemon] 应用程序崩溃 - 等待文件更改后再启动...
您提供的代码中出现了一个错误,指出在没有使用new
关键字的情况下调用了ObjectId的类构造函数。这可能是因为您需要使用new
来创建ObjectId对象。您可以将以下行更改为使用new
:
const query = { _id: new ObjectId(id) };
这应该解决您遇到的问题。
英文:
I have written a express index.js to simple crud operation in mongodb. the item is the params I can console.log as mongodb Id however, ObjectId buildin function giving me a an class constructor error that it cannot inboked without 'new'.
const express = require("express");
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
const cors = require("cors");
const app = express();
const port = process.env.PORT || 5000;
//middleware
app.use(cors());
app.use(express.json());
const uri =
"mongodb+srv://<hiddenuser>:<hiddenPass>@cluster0.9mathic.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
});
const run = async () => {
try {
const userCollection = client
.db("simple-node-mongo-server")
.collection("mongo_crud_server");
//post user data in db
app.post("/users", async (req, res) => {
const user = req.body;
console.log(user);
const result = await userCollection.insertOne(user);
res.send(result);
});
//reading data of user
app.get("/users", async (req, res) => {
const query = {};
const cursor = userCollection.find(query);
const users = await cursor.toArray();
res.send(users);
});
//deleting a user
app.delete("/users/:id", async (req, res) => {
const id = req.params.id;
// console.log('trying to delete', id);
const query = { _id: ObjectId(id) };
console.log(query)
// const result = await userCollection.deleteOne(query);
// console.log(result);
// res.send(result);
});
} finally {
}
};
run().catch(console.dir);
//raw api hit
app.get("/", (req, res) => {
res.send("Hello world");
});
app.listen(port, () => {
console.log(`listening port 5000`);
});
error it shows
C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\index.js:45
const query = { _id: ObjectId(id) };
^
TypeError: Class constructor ObjectId cannot be invoked without 'new'
at C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\index.js:45:28
at Layer.handle [as handle_request] (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\index.js:284:15
at param (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\index.js:365:14)
at param (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\index.js:376:14)
at Function.process_params (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\index.js:421:3)
at next (C:\Users\sdman\OneDrive\Documents\GitHub\mongo-project\mongo_crud_server\node_modules\express\lib\router\index.js:280:10)
Node.js v18.13.0
[nodemon] app crashed - waiting for file changes before starting...
I've tried 'ObjectID = require('mongodb').ObjectID,'
答案1
得分: 2
为了解决错误,您可以在ObjectId
之前添加new
关键字以创建该类的新实例:
const query = { _id: new ObjectId(id) };
英文:
To solve the error, you can add the new
keyword before ObjectId
to create a new instance of the class:
const query = { _id: new ObjectId(id) };
答案2
得分: 0
这部分代码:
const query = { _id: ObjectId(id) };
你所做的是正确的,将id字符串转换为MongoDB对象id,只需要稍微修改为new ObjectId(id)
,这样它会创建一个新的ObjectId实例。
英文:
this part of the code:
const query = { _id: ObjectId(id) };
you are doing right converting the id string to a MongoDB object id, just need to slightly modify to new ObjectId(id) so it creates a new instance of ObjectId
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论