跨多个模型导出并重用我的猫鼬连接 [英] Export and reuse my mongoose connection across multiple models

查看:69
本文介绍了跨多个模型导出并重用我的猫鼬连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目录结构

./lib
./lib/model1.js
./lib/model2.js

两个模型都使用mongoose连接到相同的MongoDB实例,但是定义了不同的模型:

Both models connect to the same MongoDB instance using mongoose, but define different models:

// model1.js
var mongoose = require ('mongoose');
mongoose.connect ('bla')
var db = mongoose.connection;

var schema1, model1;

db.on('error', console.error.bind(console, 'database, why you no connect?'));

db.once('open', function callback () {

  schema1 = mongoose.Schema({
    // some properties
  });

  model1 = mongoose.model1 ('model1', schema1);

});

一次创建数据库连接并将其重新用于每个模型的最佳方法是什么?最佳的目录结构是什么?也许./lib/middleware/db.js?

What is the best way to create the database connection once and reuse it for each of the models? What is the best directory structure? Maybe ./lib/middleware/db.js?

这个问题似乎很相关,但它使用的是mongodb npm模块而不是猫鼬,问题尚不清楚,并且作者的所有评论都已删除.

This question seems relevant but it's using the mongodb npm module instead of mongoose, the question is unclear, and all of the author's comments have been deleted.

推荐答案

在应用程序的启动代码中,您只需调用一次mongoose.connect.这将为您的应用程序创建默认的连接池.

You should only be calling mongoose.connect once, in your application's startup code. That will create the default connection pool for your application.

您的model1.jsmodel2.js文件通过调用mongoose.model来创建其模型,该模型将它们绑定到默认连接.

Your model1.js and model2.js files create their models via calls to mongoose.model which binds them to the default connection.

所以它实际上是由猫鼬为您处理的.

So it's actually handled for you by Mongoose.

这篇关于跨多个模型导出并重用我的猫鼬连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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