首页 > 解决方案 > 从 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;

如何避免需要在要使用模型的每个文件中创建连接?

标签: node.jsmongoosemongoose-schema

解决方案


来自猫鼬 NPM

重要的!如果您使用 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 

推荐阅读