TypeError: Cannot call class constructor ObjectId without 'new'
P粉399090746
P粉399090746 2024-01-29 08:42:04
0
1
305

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粉399090746
P粉399090746

reply all(1)
P粉692052513

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" });
  }
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!