Mongoose模型测试需要模型

pfr*_*ied 6 mocha.js mongoose node.js

我在测试我的猫鼬模型时遇到了问题

我有一个像这样的结构

  • 应用
    • 楷模
      • 地址
      • 用户
      • 组织
    • 测试

用户和组织两种模型都需要知道模型地址.我的模型结构如下:

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;
};
Run Code Online (Sandbox Code Playgroud)

在我的普通应用程序中,我需要地址才能要求用户和组织,一切都很好.我现在为用户和组织编写测试.为了让地址模型注册我调用require('../models/Address.js')如果我运行一个测试,这工作正常.但如果我批量运行所有测试我得到一个错误,因为我试图两次注册地址.

OverwriteModelError: Cannot overwrite Address model once compiled.

我该如何解决这个问题?

Leo*_*tny 13

问题是你不能两次设置猫鼬模型.解决问题的最简单方法是利用node.js require函数.

Node.js缓存所有调用以require防止模型初始化两次.但是你用模型包装你的模型.展开它们将解决您的问题:

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);
Run Code Online (Sandbox Code Playgroud)

替代解决方案是确保每个模型仅初始化一次.例如,您可以在运行测试之前初始化所有模块:

Address = require('../models/Address.js');
User = require('../models/User.js');
Organization = require('../models/Organization.js');

// run your tests using Address, User and Organization
Run Code Online (Sandbox Code Playgroud)

或者您可以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');
};
Run Code Online (Sandbox Code Playgroud)

更新:在我们的项目中,我们有/models/index.js文件来处理所有事情.首先,它要求mongoose.connect建立连接.然后它需要models目录中的每个模型并创建它的字典.所以,当我们需要一些模型(例如user)时,我们需要通过调用require('/models').user.