当我使用MongoDB Atlas连接字符串时出现循环依赖性错误

时间:2019-01-13 13:47:53

标签: mongodb mongoose circular-dependency

我试图在使用MongoDB本地实例的项目中使用MongoDB Atlas。当我将mongo URI从本地主机更改为MongoDB Atlas连接字符串时,出现循环依赖错误。

这是mu猫鼬的配置文件:

const mongoose = require('mongoose');
const util = require('util');
const debug = require('debug')('express-mongoose-es6-rest-api:index');

const config = require('./config');

// connect to mongo db
const mongoUri = config.mongo.host;
mongoose.connect(mongoUri, { useNewUrlParser: true });
mongoose.connection.on('error', () => {
  throw new Error(`unable to connect to database: ${mongoUri}`);
});

// print mongoose logs in dev env
if (config.MONGOOSE_DEBUG) {
  mongoose.set('debug', (collectionName, method, query, doc) => {
    debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc);
  });
}

我的config.js:

const Joi = require('joi');

// require and configure dotenv, will load vars in .env in PROCESS.ENV
require('dotenv').config();

// define validation for all the env vars
const envVarsSchema = Joi.object({
  NODE_ENV: Joi.string()
    .allow(['development', 'production', 'test', 'provision'])
    .default('development'),
  SERVER_PORT: Joi.number()
    .default(4040),
  MONGOOSE_DEBUG: Joi.boolean()
    .when('NODE_ENV', {
      is: Joi.string().equal('development'),
      then: Joi.boolean().default(true),
      otherwise: Joi.boolean().default(false)
    }),
  SESSION_SECRET: Joi.string().required()
    .description('Session Secret required to sign'),
  MONGO_HOST: Joi.string().required()
    .description('Mongo DB host url'),
  MONGO_PORT: Joi.number()
    .default(27017)
}).unknown()
  .required();

const { error, value: envVars } = Joi.validate(process.env, envVarsSchema);
if (error) {
  throw new Error(`Config validation error: ${error.message}`);
}

const config = {
  env: envVars.NODE_ENV,
  port: envVars.SERVER_PORT,
  mongooseDebug: envVars.MONGOOSE_DEBUG,
  sessionSecret: envVars.SESSION_SECRET,
  frontend: envVars.MEAN_FRONTEND || 'angular',
  mongo: {
    host: envVars.MONGO_HOST,
    port: envVars.MONGO_PORT
  }
};

module.exports = config;

    };

    module.exports = config;

我的.env文件:

NODE_ENV=development
SERVER_PORT=4040
SESSION_SECRET=SECRET
MONGO_HOST=mongodb+srv://Manman:MyPassword@clusterHU-kt9vc.mongodb.net/test?retryWrites=true
MEAN_FRONTEND=angular

我该怎么办才能消除此错误?

1 个答案:

答案 0 :(得分:0)

感谢github issue,我得以解决我的问题。

This comment尤其对我有所帮助。

  

删除retryWrite使问题消失了。