大佬教程收集整理的这篇文章主要介绍了node.js – 连接/断开连接到数据库的最佳做法是什么?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这是一个例子.
这是我的routes.js文件,带有路由/索引.对此路由的请求应从MongoDb数据库中获取一些日期.现在我困扰我如何连接和断开数据库.是的,我完全按照Mongoose docs中的说法连接和断开数据库,但它是在严肃的生产环境中正确的方式吗?
var express = require('express'); var router = express.Router(); var config = require('./db-config'); // I create a Mongoose instance as a module object,// as opposite to create it in every request handler function below. var mongoose = require('mongoose'); var productscheR_459_11845@a = require('../db/productscheR_459_11845@a'); // model scheR_459_11845@a is also a module-wide object // And here is a request handler function. // it is called on every request as a brand new. // I create and destroy a database connection inside this request handler router.get('/index',function(req,res,next) { // I connect to a database on every request. // Do I need to do it here in a request handler? // May I do it outside of this request handler on a module-wide level? mongoose.connect('mongodb://my_database'); // I create a new connection here in a request handler. // So it lives only during this request handler run. // Is this the right way? May I do it outside of this request handler // on a module-wide level and somehow keep this connection and use it // in every subsequent requests to this or any other route in the app? var db = mongoose.connection; db.on('connecTing',function() { console.log('connecTing'); }); db.on('connected',function() { console.log('connected'); }); db.on('open',function() { console.log('open'); }); db.on('error',console.error.bind(console,'connection error')); db.once('open',function(cb) { var Product = mongoose.model('Product',productscheR_459_11845@a); Product.find({Category: "books"},function(err,prods) { if (err) return console.error(err); // I close a connection here in a callBACk. // As soon as successfully fetched the data. // Do I need to close it after every request? // what is the right place and time to do it? db.close(disconnect); res.json(prods); }); }); })
找到了一些好的答案:
What are best practices on managing database connections in .NET?
var mongoose = require('mongoose') mongoose.connect('mongodb://localhost/dbname',function(){ console.log('mongodb connected') }) module.exports = mongoose
每个模型都应该有一个单独的模块,它接受数据库连接(post.js)
var db = require('../db.js') var Post = db.model('Post',{ username: {type: String,required: truE},body: {type: String,date: { type: Date,required: true,default: Date.Now } }) module.exports = Post
然后,只要您需要使用该数据集,只需要它并进行调用
var Post = require('/models/post') Post.save() Post.find()
以上是大佬教程为你收集整理的node.js – 连接/断开连接到数据库的最佳做法是什么?全部内容,希望文章能够帮你解决node.js – 连接/断开连接到数据库的最佳做法是什么?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。