在init函数退出后,Mongoose模型立即出现

时间:2017-03-06 01:37:45

标签: javascript node.js mongoose

修改
我想我发现了问题...... 我尝试在某个地方使用process.env.PWD,除了Mongoose之外它都可以。删除它的用法,一切都突然起作用。有人可以解释原因吗? 结束编辑

启动时,我的应用会做一些事情,比如定义路线和设置Mongoose。

/init/db.js

module.exports = function () {
    const {url, options} = getCredentials();

    mongoose.connect(url, options);

    // This requires the files that have the schemas in 'm
    loadSchemas();

    console.log(require('mongoose')); // Shows all models
};

示例架构文件(user.js)

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const User = new Schema({
    username: {type: String, required: true, unique: true},
    email: {type: String, required: true, unique: true},
    registration_date: {type: Date, default: Date.now, required: true},
    birthdate: {type: Date}
});

mongoose.model('User', User);

/init/db.js中,登录require('mongoose');仍会显示所有模型并且可以访问,在该函数调用之后,require('mongoose')上的登录显示像刚才一样的猫鼬对象创建

app.js

require(`${process.env.APP_DIR}/init/db`)();
console.log(require('mongoose')); // Not a single model in it

当正常启动应用程序时,这里没有问题,但是因为我还编写了数据库单元测试,它会因错误而崩溃

  throw new mongoose.Error.MissingSchemaError(name);
  ^
  MissingSchemaError: Schema hasn't been registered for model "User".
  Use mongoose.model(name, schema)

0 个答案:

没有答案