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!

5
  • Does this answer your question? Error: Can't set headers after they are sent to the client Commented Feb 10, 2023 at 0: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 Commented Feb 10, 2023 at 0:15
  • there are similar questions, but i couldn't find the right solution Commented Feb 10, 2023 at 0:19
  • The issue is you've used sendStatus() when you should have just used status(). This is the exact same issue as the duplicate Commented Feb 10, 2023 at 0:23
  • ... specifically this answer Commented Feb 10, 2023 at 0:48

1 Answer 1

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").

Sign up to request clarification or add additional context in comments.

2 Comments

OP will still need .status(500) for the error, otherwise it will be sent as 200
Of course, thanks @Phil . I have added more detail to my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.