node.js - Mongoose 模型测试需要模型

标签 node.js mongoose mocha.js

我在测试 Mongoose 模型时遇到问题

我有这样的结构

  • 应用程序
    • 模特
      • 地址
      • 用户
      • 组织机构
    • 测试

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

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;
};

在我的普通应用程序中,我在需要用户和组织之前需要地址,一切都很好。我现在为用户和组织编写测试。为了注册 Address 模型,我调用了 require('../models/Address.js') 如果我运行一个测试,它就可以正常工作。但是,如果我批量运行所有测试,则会出现错误,因为我尝试注册地址两次。

OverwriteModelError:编译后无法覆盖地址模型。

我该如何解决这个问题?

最佳答案

问题是你不能设置 Mongoose 模型两次。解决问题的最简单方法是利用 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);

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

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 建立连接。然后它需要 models 目录中的每个模型并创建它的字典。因此,当我们需要一些模型(例如 user)时,我们通过调用 require('/models').user 来请求它。

关于node.js - Mongoose 模型测试需要模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14644742/

相关文章:

node.js - 无法在命令提示符下运行node.js程序

node.js - 如何使用 Passport 验证 React 应用程序?

javascript - Nodejs Mocha : Unable to test a POST and GET by ID

javascript - Sinon.js spy.called 不适用于 RPC

javascript - mocha——以编程方式要求

javascript - 在沙箱中执行代码,模块在相同的上下文中

node.js - 关于 Node.js Bootstrap npm 包最近被弃用了吗?

javascript - 更新 mongodb 中的数组

node.js - 如何在 Mongoose 中为特定用户角色创建对象?

Node.js 堆栈跟踪信息