0

I have been learninng NodeJS and mongoDB by youtube, but unfortunately i faced with this problem, and here is my code file! thank you in advance!

db.js

const { MongoClient } = require("mongodb");

let dbConnection;

module.exports = {
  connectToDb: (cb) => {
    MongoClient.connect("mongodb://localhost:27017/bookstore")
      .then((res) => {
        dbConnection = res.db();
        return cb();
      })
      .catch((error) => {
        console.log(error);
        return cb(error);
      });
  },
  getDb: () => dbConnection,
};

index.js

const express = require("express");
const { connectToDb, getDb } = require("./db");

// init app and middleware
const app = express();

//db connection
let db;

connectToDb((xato) => {
  if (!xato) {
    app.listen(3000, () => {
      console.log("The 3000 port is installed");
    });
    db = getDb();
    return db;
  }
});

//routes
app.get("/bookstore", (req, res) => {
  let mybook = [];
  // the collection name from mongoDB
  db.collection("bookstore")
    .find()
    .sort({ author: 1 })
    .forEach((book) => mybook.push(book))
    .then(() => {
      return res.sendStatus(200).json(mybook);
    })
    .catch(() => {
      return res.sendStatus(500).send("there were an error");
    });
  // res.json({ MyWords: "I am coming from json res" });
});

it must return data from local mongodb database. But it is facing with the problem. Please give me a solution!

  • Does this answer your question? [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – Phil Feb 10 '23 at 00:14
  • The error has nothing to do with MongoDB. Did you try searching for that error message? I couldn't even remove _"(MongoDB)"_ from the title because Stack Overflow matched it to an existing question – Phil Feb 10 '23 at 00:15
  • there are similar questions, but i couldn't find the right solution – Sardor Sirojov Feb 10 '23 at 00:19
  • The issue is you've used `sendStatus()` when you should have just used `status()`. This is the exact same issue as the duplicate – Phil Feb 10 '23 at 00:23
  • ... specifically [this answer](https://stackoverflow.com/a/59408191/283366) – Phil Feb 10 '23 at 00:48

1 Answers1

3

both .sendStatus and .json will try to response to client. So the second call will result in this error.

Just use res.json(mybook) and res.send("there were an error") is enough.

In case you want to maintain status code and also send data. Use res.status(500).send("there were an error").

hungtran273
  • 1,180
  • 9
  • 11