当我尝试从 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" });
});
});
想知道如何消除此错误以及导致此错误的原因
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
尝试下面的代码,它对我有用,只需将 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" }); } });