Saving data to mongodb database issues using nodejs and express

1.4k views Asked by At

I am having an issue with trying to save data parsed from the browser to my mongodb database it would be great if someone could explain to me why I am getting the error I am and how to fix it, thanks.

App.js:

var print = require('./print');
var port = 1338;
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:1337/testdb';
MongoClient.connect(url, function(err, db) {
    var collection = db.collection('users');
    if (err) {
        console.log('Unable to connect to the mongoDB server. Error:', err);
    } else {
        console.log('Connection established to', url);
    }
    app.use(bodyParser.urlencoded({ extended: true }));
    app.set('view engine', 'ejs');
    app.get('/', function(req, res) {
        res.render("post");
        print("All is in order");
    })
    var collection = db.collection('users');
    var name = app.post('/post', function(req, res) {
        res.send('You sent the name "' + req.body.name + '".');
        var name = req.body.name
        var user1 = { "username": name };
        collection.insert(user1, function(err, result) {
            if (err) {
                console.log(err);
            } else {
                console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
            }
        })
    });
    app.listen(port, function() {
        print(`listening on ${port}`);
    })
    db.close();
})

Post.ejs:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>CSS3 Contact Form</title>
</head>

<body>
    <div id="contact">
        <h1>Send an email</h1>
        <form action="http://127.0.0.1:1338/post" method="post">
            <fieldset>
                <label for="name">Name:</label>
                <input type="text" id="name" name="name" placeholder="Enter your full name" />
                <label for="email">Email:</label>
                <input type="email" id="email" placeholder="Enter your email address" />
                <label for="message">Message:</label>
                <textarea id="message" placeholder="What's on your mind?"></textarea>
                <input type="submit" value="Send message" />
            </fieldset>
        </form>
    </div>
</body>

</html>

Error:

    { MongoError: server instance pool was destroyed
        at Function.MongoError.create (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\error.js:29:11)
        at basicWriteValidations (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\topologies\server.js:446:51)
        at Server.insert (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\topologies\server.js:532:16)
        at Server.insert (C:\Users\Programming\Documents\Web_Repo\\node_modules\mongodb\lib\server.js:383:17)
        at executeCommands (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\bulk\ordered.js:455:23)
        at OrderedBulkOperation.execute (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\bulk\ordered.js:508:10)
        at bulkWrite (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:652:8)
        at Collection.insertMany (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:522:44)
        at Collection.insert (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:824:15)
        at C:\Users\Programming\Documents\Web_Repo\app.js:36:18
      name: 'MongoError',
      message: 'server instance pool was destroyed' }
1

There are 1 answers

4
Mukul Jain On BEST ANSWER

Looks like Mukesh already told you the solution but like he mentioned your code structure can be improved.

So here's how I would do it,

Config file ~config.js

module.exports = {
    localUrl: 'mongodb://localhost/testDb',
    port: 1338
};

main file

var print = require('./print');
var express = require("express");
var app = express();

var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var config = require('./config.js');

app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
    res.render("post");
    print("All is in order");
})

app.listen(config.port, function() {
   print(`listening on ${config.port}`);
})

MongoClient.connect(config.localUrl, function(err, db) {
    if(err) {
      console.log('Unable to connect to the mongoDB server. Error:', err); 
      return; 
    }
    var collection = db.collection('users');
    app.post('/post', function(req, res) {
        res.send('You sent the name "' + req.body.name + '".');
        collection.insert({
         username : req.body.name
        }, function(err, result) {
            if (err) {
                console.log(err); 
                db.close();
                return;
            } 
            db.close();
        })
    });

})