首頁  >  問答  >  主體

TypeError:如果沒有“new”,則無法呼叫類別建構子 ObjectId

當我嘗試從 mongodb 取得文件時遇到此錯誤 我是第一次使用 mongo,如果有人能幫助我,那就太好了

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

想知道如何消除此錯誤以及導致此錯誤的原因

P粉399090746P粉399090746264 天前317

全部回覆(1)我來回復

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

    回覆
    0
  • 取消回覆