我无法从MongoDB ObjectId类构造函数中删除数据。

huangapple go评论65阅读模式
英文:

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(&quot;express&quot;);
const { MongoClient, ServerApiVersion, ObjectId } = require(&quot;mongodb&quot;);
const cors = require(&quot;cors&quot;);
const app = express();
const port = process.env.PORT || 5000;
//middleware
app.use(cors());
app.use(express.json());
const uri =
&quot;mongodb+srv://&lt;hiddenuser&gt;:&lt;hiddenPass&gt;@cluster0.9mathic.mongodb.net/?retryWrites=true&amp;w=majority&quot;;
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
});
const run = async () =&gt; {
try {
const userCollection = client
.db(&quot;simple-node-mongo-server&quot;)
.collection(&quot;mongo_crud_server&quot;);
//post user data in db
app.post(&quot;/users&quot;, async (req, res) =&gt; {
const user = req.body;
console.log(user);
const result = await userCollection.insertOne(user);
res.send(result);
});
//reading data of user
app.get(&quot;/users&quot;, async (req, res) =&gt; {
const query = {};
const cursor = userCollection.find(query);
const users = await cursor.toArray();
res.send(users);
});
//deleting a user
app.delete(&quot;/users/:id&quot;, async (req, res) =&gt; {
const id = req.params.id;
// console.log(&#39;trying to delete&#39;, 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(&quot;/&quot;, (req, res) =&gt; {
res.send(&quot;Hello world&quot;);
});
app.listen(port, () =&gt; {
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 &#39;new&#39;
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

huangapple
  • 本文由 发表于 2023年2月24日 14:33:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553265.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定