TypeError:如果沒有'new”,則無法呼叫類別建構子 ObjectId
P粉399090746
P粉399090746 2024-01-29 08:42:04
0
1
312

當我嘗試從 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粉399090746
P粉399090746

全部回覆(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" });
  }
});
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!