人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動(dòng)態(tài)

關(guān)于mongoose連接mongodb重復(fù)訪問報(bào)錯(cuò)的解決辦法

發(fā)布日期:2021-12-21 11:32 | 文章來源:CSDN

具體代碼如下所示:

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ù)庫(kù)連接?

解決辦法如下所示:

新建一個(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)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時(shí)開通

自選配置、實(shí)時(shí)開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對(duì)1客戶咨詢顧問

在線
客服

在線客服:7*24小時(shí)在線

客服
熱線

400-630-3752
7*24小時(shí)客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部