The specific code looks like this:
var express = require (' Express ');
var mongoose = require (' Mongoose ');
var router = Express. Router ();
var person = Mongoose.model (' person ', {
id:number,
name:string
});
/* Add/*
router.get ('/insert ', function (req, res) {
var student = new Person ({
id:1,
name: "Huop"
});
Mongoose.connect ("Mongodb://localhost:27017/test");
Student.save (function (e, product, numberaffected) {
if (e) res.send (e.message);
var html = "
new data is:" + json.stringify (product);
HTML + + "
affect the amount of data is:" + numberaffected;
Res.send (HTML);
}
); Router.get ('/find ', function (request, response) {
mongoose.connect ("Mongodb://localhost:27017/test");
Person.find ({
id:1
}, Function (e, docs) {
if (e) response.send (e.message);
var html = "The
queried data is:" + json.stringify (docs);
Response.send (HTML);
});
The above code can be performed normally, but there is a problem, is the first visit when normal, but the refresh will be an error, trying to open unclosed connection.undefined
error:trying to open unclosed connection.
Should be repeatedly open connection failure error, so need to close the connection, I added a section of the code to close the connection, the result of the query results: The query to the data: Unde
So how do you handle the MongoDB database connection?
The solution is as follows:
Create a new mongoose.js:
var mongoose = require (' Mongoose ');
Mongoose.connect (' Mongodb://localhost/nuaidibi ');
Module.exports = Mongoose;
In each module, reference
var mongoose = require ('./mongoose.js '); Use the same as the following, without the switch connection.