Kiran
Kiran

Reputation: 2417

How to send response to front end after execution of mongodb request?

I am creating sign up page. Where, I first check whether user email already present in our mongodb database or not. If it is present then I want to send error message to frontEnd. However, I am failing to do that, I think it might be because of asynchronous behavior of JavaScript.My Code is as following:

var myObj , myJSON
var SignUpUserEmail, SignUpUserPassword, SignUpUserName, SignUpErr
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  var q = url.parse(req.url, true).query 
  SignUpUserEmail = q.SignUpUserEmail
  SignUpUserPassword = q.SignUpUserPassword
  SignUpUserName = q.SignUpUserName

  MongoClient.connect("mongodb://localhost:27017/ABC",function(err, 
  database) {
    if (err) throw err;
    var db=database.db('ABC')

    let findOneParam = {"UserEmail":SignUpUserEmail} 
    db.collection('Profiles').findOne(findOneParam, function(err, result) {
    if (err) throw err;
    if(!result) {
      db.collection('Profiles', function(err, collection){
        if (err) throw err;
        collection.insertOne({"UserId":"ProfileA0001",
                          "UserEmail":SignUpUserEmail,
                          "UserPassword":SignUpUserPassword,
                          "UserName":SignUpUserName,
                          "IsEmailAuthenticated":"false"
                        }, function(err, res){
          if (err) throw err;
          SignUpErr = "document inserted"
          console.log("SignUpErr inside:", SignUpErr)
        })
      })
    } else {
      SignUpErr = "Email already has been registered."
      console.log("SignUpErr inside:", SignUpErr)
    }
  })
})

  console.log("SignUpErr outside:", SignUpErr)
  myObj = {"SignUpErr":SignUpErr};
  myJSON = JSON.stringify(myObj);
  res.end(myJSON);
}).listen(9000);

Note: "SignUpErr inside:" giving correct result. however, "SignUpErr outside:" shows it as undefined.

Upvotes: 0

Views: 1398

Answers (2)

Sridhar
Sridhar

Reputation: 11786

Note: "SignUpErr inside:" giving correct result. however, "SignUpErr outside:" shows it as undefined.

This is because of the asynchronous nature of the nodejs. SignUpErr will be undefined until the time it is initialized within the db.collection('Profiles',function(){}) call.

So, to fix this, you need to send response within db.collection('Profiles',function(){}). that's, after the initilization.

Making those changes to your code,

'use strict';

const http = require('http');

http.createServer(function (req, res) {

  res.statusCode = 200; // Setting the status code
  res.setHeader('Content-Type', 'text/plain');  // Setting the content-type for response

  let {SignUpUserEmail, SignUpUserPassword, SignUpUserName} = url.parse(req.url, true).query;

  MongoClient.connect("mongodb://localhost:27017/ABC", function (err, database) {
    if (err) {
      throw err;
    }

    let db = database.db('ABC');

    db.collection('Profiles').findOne({
      UserEmail: SignUpUserEmail
    }, function (err, result) {
      if (err) {
        throw err
      }

      if (result) {
        let msg = "Email already has been registered.";
        console.log("SignUpErr inside:", msg);

        return res.end(JSON.stringify({
          SignUpErr: "document inserted"
        }));
      }

      db.collection('Profiles', function (err, collection) {
        if (err) throw err;
        collection.insertOne({
          "UserId": "ProfileA0001",
          "UserEmail": SignUpUserEmail,
          "UserPassword": SignUpUserPassword,
          "UserName": SignUpUserName,
          "IsEmailAuthenticated": "false"
        }, function (err, dbresult) {
          if (err) {
            throw err;
          }
          let msg = "document inserted";
          console.log("SignUpErr inside:", msg);

          return res.end(JSON.stringify({
            SignUpErr: "document inserted"
          }));

        })
      });

    });
  });

}).listen(9000);

Upvotes: 1

xan_z
xan_z

Reputation: 226

I usually use express as my web framework which comes with res.send() method, where you can send your response . I usually build a JSON response, and send it as res.send(JSON.stringify(data)); There is also res.JSON(data). If you wish to use HTTP module , then you can use res.end() method. Details are provided here . Hope this helps.

Upvotes: 0

Related Questions