About Mongoose Connection MongoDB repeated access error resolution _MARIADB

Source: Internet
Author: User
Tags json mongodb

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.