關於mongoose串連mongodb重複訪問報錯的解決辦法_mariadb

來源:互聯網
上載者:User

具體代碼如下所示:

var express = require('express');var mongoose = require('mongoose');var router = express.Router();var Person = mongoose.model('Person',{ id:Number, name:String});/*新增*/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 = "新增的資料為:" + JSON.stringify(product);  html += "影響的資料量為:" + 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 = " 查詢到的資料為:" + JSON.stringify(docs);  response.send(html); });});

以上代碼可以正常執行,但是有個問題,就是第一次訪問的時候正常,但是重新整理一遍就會報錯,Trying to open unclosed connection.undefined
Error: Trying to open unclosed connection.

應該是重複開啟串連失敗報錯,所以需要關閉串連,我加了一段關閉串連的代碼,結果查詢結果就成了:查詢到的資料為:unde

那麼該如何處理mongodb資料庫連接?

解決辦法如下所示:

建立一個mongoose.js:

var mongoose = require(‘mongoose');mongoose.connect(‘mongodb://localhost/nuaidibi');module.exports = mongoose;

每個module中,引用

var mongoose = require('./mongoose.js');下面使用就一樣了,不用開關串連。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.