Heim  >  Fragen und Antworten  >  Hauptteil

TypeError: Der Klassenkonstruktor ObjectId kann nicht ohne „new“ aufgerufen werden.

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粉399090746P粉399090746264 Tage vor319

Antworte allen(1)Ich werde antworten

  • P粉692052513

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

    尝试下面的代码,它对我有用,只需将 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" });
      }
    });

    Antwort
    0
  • StornierenAntwort