關(guān)于mongoose連接mongodb重復(fù)訪問報(bào)錯(cuò)的解決辦法
具體代碼如下所示:
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 = "
新增的數(shù)據(jù)為:" + JSON.stringify(product);
html += "
影響的數(shù)據(jù)量為:" + 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 = "
查詢到的數(shù)據(jù)為:" + JSON.stringify(docs);
response.send(html);
});
});
以上代碼可以正常執(zhí)行,但是有個(gè)問題,就是第一次訪問的時(shí)候正常,但是刷新一遍就會(huì)報(bào)錯(cuò),Trying to open unclosed connection.undefined
Error: Trying to open unclosed connection.
應(yīng)該是重復(fù)打開連接失敗報(bào)錯(cuò),所以需要關(guān)閉連接,我加了一段關(guān)閉連接的代碼,結(jié)果查詢結(jié)果就成了:查詢到的數(shù)據(jù)為:unde
那么該如何處理mongodb數(shù)據(jù)庫連接?
解決辦法如下所示:
新建一個(gè)mongoose.js:
var mongoose = require(‘mongoose'); mongoose.connect(‘mongodb://localhost/nuaidibi'); module.exports = mongoose;
每個(gè)module中,引用
var mongoose = require('./mongoose.js');下面使用就一樣了,不用開關(guān)連接。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信