node.js - 从 mongoose.connect() 迁移到 mongoose.createConnection() 时遇到问题
问题描述
使用 mongoose.createConnection 时,如何从路由器访问模型?我每次都必须 mongoose.createConnection 吗?我使用文档中的这种模式:
//app.js
const mongoose = require('mongoose');
const conn = mongoose.createConnection(process.env.MONGODB_URI);
conn.model('User', require('../schemas/user'));
conn.model('PageView', require('./schemas/pageView'));
module.exports = conn;
现在,这不起作用:
//router.js
const PageView = require('./schemas/pageView');
..我知道它不起作用,因为我不再从模式文件中导出模型,只是模式:
// ./schemas/pageView.js
module.exports = PageViewSchema;
在使用 createConnection 之前,我在 app.js 中使用了默认的mongoose.connect(),所以我只需导出模型,如下所示:
// ./schemas/pageView.js
const PageView = mongoose.model("PageView", PageViewSchema);
module.exports = PageView;
如何避免需要在要使用模型的每个文件中创建连接?
解决方案
重要的!如果您使用 mongoose.createConnection() 打开了单独的连接,但尝试通过 mongoose.model('ModelName') 访问模型,它将无法按预期工作,因为它没有连接到活动的数据库连接。在这种情况下,通过您创建的连接访问您的模型:
const conn = mongoose.createConnection('your connection string'); const MyModel = conn.model('ModelName', schema); const m = new MyModel; m.save(); // works
对比
const conn = mongoose.createConnection('your connection string'); const MyModel = mongoose.model('ModelName', schema); const m = new MyModel; m.save(); // does not work b/c the default connection object was never connected
推荐阅读
- javascript - 保存过滤器,没有数据 WebDataRocks
- javascript - 为什么 Django 不能正确加载我的 javascript 文件?
- python - 尝试 POST 到 Flask 应用程序时出现 HTTP 405 错误
- asp.net-core - 如何在 Identity Server 4 中验证 AAD 用户?
- php - Symfony 注释配置中的正则表达式
- vue.js - Vue + webpack,将字体文件转换为base64
- php - 如何修复 Wordpress PHP 致命错误:mysql2date()
- python - 字符/数字的边界框检测
- reactjs - 无法将 response.data 放入我的 React.js 状态?(express.js)
- bash - bash 脚本:删除其他 bash 脚本中的所有注释