mongoose模型testing需要模型
我有一个testing我的mongoose模型的问题
我有一个像
- 应用
- 楷模
- 地址
- 用户
- 组织
- testing
- 楷模
用户和组织都需要知道型号Address。 我的模型结构如下:
module.exports = function (mongoose, config) { var organizationSchema = new mongoose.Schema({ name : { type : String }, addresses : { type : [mongoose.model('Address')] } }); var Organization = mongoose.model('Organization', organizationSchema); return Organization; };
在我的正常的应用程序,我需要地址之前要求用户和组织,一切都很好。 我现在为用户和组织编写testing。 为了让地址模型注册,我打电话require('../models/Address.js')
这工作正常,如果我运行一个testing。 但是,如果我在批处理中运行所有testing,我得到一个错误,因为我试图注册地址两次。
OverwriteModelError: Cannot overwrite Address model once compiled.
我如何解决这个问题?
问题是你不能设置mongoose模型两次。 解决你的问题最简单的方法是利用node.js require
函数。
Node.js会caching所有调用,以防止模型初始化两次。 但是你用function包装你的模型。 解开他们将解决您的问题:
var mongoose = require('mongoose'); var config = require('./config'); var organizationSchema = new mongoose.Schema({ name : { type : String }, addresses : { type : [mongoose.model('Address')] } }); module.exports = mongoose.model('Organization', organizationSchema);
替代解决scheme是确保每个模型只初始化一次。 例如,您可以在运行testing之前初始化所有模块:
Address = require('../models/Address.js'); User = require('../models/User.js'); Organization = require('../models/Organization.js'); // run your tests using Address, User and Organization
或者你可以添加try catch
语句到你的模型来处理这个特殊情况:
module.exports = function (mongoose, config) { var organizationSchema = new mongoose.Schema({ name : { type : String }, addresses : { type : [mongoose.model('Address')] } }); try { mongoose.model('Organization', organizationSchema); } catch (error) {} return mongoose.model('Organization'); };
更新:在我们的项目中,我们有/models/index.js
文件来处理一切。 首先,它调用mongoose.connect
build立连接。 然后,它需要models
目录中的每个模型,并创build它的字典。 所以,当我们需要一些模型(例如user
)时,我们需要调用require('/models').user
。
最佳解决scheme(IMO):
try { mongoose.model('config') } catch (_) { mongoose.model('config', schema) }
这个问题已经有了答案,但为了一个独特的方式来完成这个检查https://github.com/fbeshears/register_models 。 此示例项目使用register_models.js,其中包含文件名称数组中的所有模型。 它工作得非常好,你可以随时随地find你需要的所有模型。 请记住,node.js的caching将在运行时caching项目中的对象。
我使用try / catch解决这个问题,它工作正常。 但我认为这不是做这件事的最好方法。
try{ var blog = mongoose.model('blog', Article); } catch (error) {}