skip to Main Content

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:UserssdmanOneDriveDocumentsGitHubmongo-projectmongo_crud_serverindex.js:45
      const query = { _id: ObjectId(id) };
                           ^

TypeError: Class constructor ObjectId cannot be invoked without 'new'
    at C:UserssdmanOneDriveDocumentsGitHubmongo-projectmongo_crud_serverindex.js:45:28
    at Layer.handle [as handle_request] (C:UserssdmanOneDriveDocumentsGitHubmongo-projectmongo_crud_servernode_modulesexpresslibrouterlayer.js:95:5)
    at next (C:UserssdmanOneDriveDocumentsGitHubmongo-projectmongo_crud_servernode_modulesexpresslibrouterroute.js:144:13)
    at Route.dispatch (C:UserssdmanOneDriveDocumentsGitHubmongo-projectmongo_crud_servernode_modulesexpresslibrouterroute.js:114:3)
    at Layer.handle [as handle_request] (C:UserssdmanOneDriveDocumentsGitHubmongo-projectmongo_crud_servernode_modulesexpresslibrouterlayer.js:95:5)
    at C:UserssdmanOneDriveDocumentsGitHubmongo-projectmongo_crud_servernode_modulesexpresslibrouterindex.js:284:15
    at param (C:UserssdmanOneDriveDocumentsGitHubmongo-projectmongo_crud_servernode_modulesexpresslibrouterindex.js:365:14)
    at param (C:UserssdmanOneDriveDocumentsGitHubmongo-projectmongo_crud_servernode_modulesexpresslibrouterindex.js:376:14)
    at Function.process_params (C:UserssdmanOneDriveDocumentsGitHubmongo-projectmongo_crud_servernode_modulesexpresslibrouterindex.js:421:3)
    at next (C:UserssdmanOneDriveDocumentsGitHubmongo-projectmongo_crud_servernode_modulesexpresslibrouterindex.js:280:10)

Node.js v18.13.0
[nodemon] app crashed - waiting for file changes before starting...

I’ve tried ‘ObjectID = require(‘mongodb’).ObjectID,’

2

Answers


  1. 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) };
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search