使用nodejs和express将数据保存到mongodb数据库问题

时间:2016-12-28 02:14:38

标签: node.js mongodb express ejs body-parser

我在尝试将从浏览器解析的数据保存到我的mongodb数据库时遇到问题,如果有人可以向我解释为什么我会收到错误以及如何修复它,那将会很棒。谢谢。

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>

错误:

    { 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 个答案:

答案 0 :(得分:0)

看起来Mukesh已经告诉过你解决方案,但他提到你的代码结构可以改进。

所以,我会这样做,

配置文件~config.js

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

主文件

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();
        })
    });

})