简体   繁体   中英

I am unable to save data to my mongodb Atlas database

Github repo. I am trying to use MongoDB Atlas database with my node JS Login & Signup app for storing data. The problem is that the data is not saving to the database or in other words the request isn't going through even if my app is connected to Atlas. Full code available on www.github.com/tahseen09/login

 // Connection to mongodb atlas const uri = "mongodb+srv://tahseen09:<PASSWORD>@cluster0-pirty.mongodb.net/userdb" MongoClient.connect(uri, function(err, client) { if(err) { console.log('Error occurred while connecting to MongoDB Atlas...\\n',err); } console.log('Connected to Atlas'); const collection = client.db("userdb").collection("credentials"); client.close(); }); //New User Registration app.post('/register', function(req,res){ var cred= new credential(); cred.uname=req.body.uname; const hash = bcrypt.hashSync(req.body.password, 10); cred.password=hash; collection.save(function(err,newuser){ if(err){ res.status(500).send("Username exists"); } else{ res.status(200).send("New User Created"); } }) })

The code that is important is attached as a snippet and the rest of the code is available on www.github.com/tahseen09/login Note: I am running this app on localhost.

Lets step through the code to see what happens:

 MongoClient.connect(uri, function(err, client) {

A connection to mongodb is created, then somewhen the connection is established or it fails, then the callback gets called back. Now you create a local variable holding the database reference:

 const collection = client.db("userdb").collection("credentials");

And then you close the connection:

 client.close();

Then the callback ends:

 });

which means that a variables inside ( connection ) can't be accessed anymore and get therefore recycled.

Now somewhen (that might even happen before the db connection gets established), someone requests the webpage and you try to do:

 collection.save(/*...*/);

That won't work for various reasons:

1) The db might not even be opened

2) If it was opened already, it was also closed already.

3) Even if it is open at the moment, you still cannot access connection as it is not in scope.

Now to resolve that we have to:

1) only start the webserver when the db connection is establishee

2) don't close the connection

3) expose the connection so that it can be used elsewhere

For that it makes sense to create a function that establishes the connection and calls back with the db:

 function withCredentials(callback) {
   const uri = "mongodb+srv://tahseen09:<PASSWORD>@cluster0-pirty.mongodb.net/userdb"
   MongoClient.connect(uri, function(err, client) {
    if(err) {
      console.log('Error occurred while connecting to MongoDB Atlas...\n',err);
    } else {
      console.log('Connected to Atlas');
     const collection = client.db("userdb").collection("credentials");
     callback(collection);
    }
  });
}

So now you can use that:

 withCredentials(function(credentials) {
   app.post('/register', function(req,res){    
     const cred = { };
     cred.uname = req.body.uname;
     cred.password = bcrypt.hashSync(req.body.password, 10);
     credentials.insertOne(cred, function(err,newuser){
        if(err){
          res.status(500).send("Username exists");
        } else {
          res.status(200).send("New User Created");
        }
     })
   });
 });

Let me describe your flow so you can understand wrong point there :)

  1. Connect to MongoDB
  2. Create reference to the collection
  3. Close connection
  4. When someone tries to access /register route, you already have closed connection by that time. Thus, any operation attempt to the database will end up with connection error.

From the documentation it's recommended calling MongoClient.connect once and reusing the database variable returned by the callback, ie do not close connection manually, driver will just create and use pool of connections, so don't worry about closing connection. Check out example code in the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM