search

Home  >  Q&A  >  body text

TypeError: Cannot call class constructor ObjectId without 'new'

I get this error when I try to get a document from mongodb I'm using mongo for the first time, it would be great if anyone could help me

const express = require("express");
const { ObjectId } = require("mongodb");
const { connectToDb, getDb } = require("./db");

const app = express();

//db connection
let db;
connectToDb((err) => {
  if (!err) {
    app.listen(3000, () => {
      console.log("App listerning on Port :3000");
    });
    db = getDb();
  }
});

//route connections
app.get("/books", (req, res) => {
  let books = [];
  db.collection("books")
    .find()
    .sort({ author: 1 })
    .forEach((book) => books.push(book))
    .then(() => {
      res.status(200).json(books);
    })
    .catch(() => {
      res.status(500).json({ error: "Couldn't fetch the documents" });
    });
});

app.get("/books/:id", (req, res) => {
  db.collection("books")
    .findOne({ _id: ObjectId("req.params.id") })
    .then((doc) => {
      res.status(200).json(doc);
    })
    .catch((err) => {
      res.status(500).json({ error: "could not fetch the document" });
    });
});

Want to know how to eliminate this error and what causes it

P粉399090746P粉399090746295 days ago343

reply all(1)I'll reply

  • P粉692052513

    P粉6920525132024-01-30 00:51:48

    Try the code below, it worked for me, just store new ObjectId() in variable (id) and then access the variable inside the method as shown below

    const { ObjectId } = require("mongodb");
    
    app.get("/books/:id", (req, res) => {
      const id = new ObjectId(req.params.id);
    
      if (ObjectId.isValid(id)) {
        db.collection("books")
          .findOne({ _id: id })
          .then((doc) => {
            res.status(200).json(doc);
          })
          .catch((err) => {
            res.status(500).json({ error: "Could not fetch the documents" });
          });
      } else {
        res.status(500).json({ error: "Not a valid doc id" });
      }
    });

    reply
    0
  • Cancelreply