0

I have written a small code in node.js to insert a document in MongoDB collection. But as I make a request for profile route I get the error I mentioned in the title. I can't figure out which line is causing the problem, maybe it is the one after insertOne method. The code is:

http
  .createServer((req, res) => {

    res.writeHead(200, { "Content-Type": "text/html" });
    var url = req.url;

    if (url == "/") {
      res.end("<h1>Basic route</h1>");
    } else if (url == "/profile") {

      mydb
        .collection("record")
        .insertOne({ username: "vipul", password: "vipul1234" }, (err, result) => {
          if (err) res.end(err);
          else res.end("inserted successfully");
        });
    } else if (url == "/about") {
      res.end("<h1>About Us Page</h1>");
    } else {
      let date = Date();
      res.end("<h1>Incorrect URL</h1><h2>", date, "</h2>");
    }
  })
  .listen(3000, () => {
    console.log("Server listening at port 3000");
  });

Please guide me through. I am a beginner to Node!

4
  • res.end doesn't take objects. so res.end(err); might fail. Try res.end(err.message); Commented Aug 3, 2019 at 17:45
  • Also don't think that res.end() will accept comma-delimited parameters... Commented Aug 4, 2019 at 0:24
  • Can you share your mongodb config file? Commented Aug 4, 2019 at 7:20
  • I've made some changes and now it is working!! Commented Aug 4, 2019 at 9:49

1 Answer 1

1

About this:

if (err)
    res.end(err);
else
    res.end("inserted successfully");

res.end does not accept the error itself. You have to pass it a string or a buffer.

(See more here: https://nodejs.org/api/http.html#http_response_end_data_encoding_callback)

You can try this:

if (err)
    res.end(err.message);
else
    res.end("inserted successfully");
Sign up to request clarification or add additional context in comments.

1 Comment

I have corrected that and it has worked but now it is giving MongoError there are no users authenticated

Your Answer

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