在猫鼬中跨整个应用程序共享数据库连接 [英] sharing db connection across entire app in mongoose

查看:92
本文介绍了在猫鼬中跨整个应用程序共享数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用最新的猫鼬更新,您将无法再按照我的方式对用户进行建模.我需要在整个应用程序中共享相同的数据库连接.

With the latest mongoose update, you can no longer user models the way I've been doing. I need to share the same db connection across my entire app.

https://github.com/LearnBoost/mongoose/issues/1249

这是不再有效的旧方法:

Here is the old way which no longer works:

./models/user.js

./models/user.js

var mongoose = require('mongoose'), cfg = require('../config')
, Schema = mongoose.Schema
, db = mongoose.createConnection(cfg.mongo.uri, cfg.mongo.db);
...

module.exports = db.model('Item', ItemSchema);

如何按照上面github问题中的建议重新使用数据库连接?

How can I re-use db connection as suggested in github issue above?

我在代码库中的多个不同位置使用了var User = require('./models/user');.

I'm using var User = require('./models/user'); in several different places in my code base.

推荐答案

选项1:使用共享对象

我的模型代码看起来很相似,但是没有重复需要模块,而是在应用程序启动时只需要它们一次,然后将结果分配给共享对象.例如,如果您使用快递应用,则可以使用app.locals.models.User = require('./models/user');之类的东西.这样,任何有权访问app的人都可以看到您的模型,而无需要求.

Option 1: Use a shared object

My model code looks similar, but instead of repeatedly requiring the modules I just require them once when the application starts and then assign the results to a shared object. For example if you are using an express app you could just so something like app.locals.models.User = require('./models/user');. Then anything with access to the app can see your models without needing a require.

您可以这样定义用户模块:

You can define your user module like so:

var mongoose = require('mongoose');

var userSchema = new mongoose.Schema({name: String});

var User = null;

module.exports = function(db) {
  if (db && User === null) {
    User = db.model('User', userSchema);
  }
  return User;
};

启动应用程序时,您只需要:require('./models/user')(db).您的应用程序中的其他模块随后需要删除db参数,因为User只会被设置一次.

When you start your application you simply need to: require('./models/user')(db). Subsequent requires by other modules in your application can drop the db paramater, as User will only be set once.

这篇关于在猫鼬中跨整个应用程序共享数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆