TypeError: Der Klassenkonstruktor ObjectId kann nicht ohne „new' aufgerufen werden.
P粉399090746
P粉399090746 2024-01-29 08:42:04
0
1
311

Ich habe diese Fehlermeldung erhalten, als ich versuche, das Dokument von mongodb abzurufen Ich benutze Mongo zum ersten Mal, es wäre toll, wenn mir jemand helfen könnte

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" });
    });
});

Möchten Sie wissen, wie Sie diesen Fehler beheben können und was ihn verursacht

P粉399090746
P粉399090746

Antworte allen(1)
P粉692052513

尝试下面的代码,它对我有用,只需将 new ObjectId() 存储在变量 (id) 中,然后在方法内部访问该变量,如下所示

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" });
  }
});
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!