具体代码如下所示:
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');下面使用就一样了,不用开关连接。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“关于mongoose连接mongodb重复访问报错的解决办法”评论...
更新日志
2024年07月01日
2024年07月01日
- 瑞鸣音乐《中国音乐地图之听见河南豫剧经典唱段》2020[WAV分轨]
- 【伊比萨沙发】VA-2024-IbizaSpring2024(LoungeCocktailsfromtheHeart)[FLAC]
- 群星《世界顶级汽车音响试音王》4K金碟16CD[WAV+CUE]
- 群星-音效环绕天碟《极致环绕人声天碟天品》7CD[WAV]
- 泰拉克SACD古典试音碟7SACD-ISO
- 群星《红歌宝典》20CD[WAV/分轨]
- 《101系列:好歌101首 细听年代精选》[WAV+CUE][3.6GB]
- 《101系列 6CD 国语经典101首歌曲 张学友 王菲代表作》[APE+CUE][2.8GB]
- 《101系列:国语经典101 VOL2 6CD 精选最经典101首》[WAV+CUE][2.3GB]
- 群星《十年网络红歌》15CD[WAV分轨]
- 宝丽金-环球10周年至50周年经典金曲15CD[低速原抓WAV+CUE]
- FIM唱片《十大男伶》[低速原抓WAV+CUE]
- 《101系列:情歌101 6CD》[WAV+CUE][3.1GB]
- 庄心妍《降调版合集》[320K/MP3][52.96MB]
- 庄心妍《降调版合集》[FLAC/分轨][118.78MB]