I get this error when I try to get a document from mongodb I'm using mongo for the first time, it would be great if anyone could help me
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" }); }); });
Want to know how to eliminate this error and what causes it
Try the code below, it worked for me, just store new ObjectId() in variable (id) and then access the variable inside the method as shown below