【问题标题】:Json config file for mongodbmongodb 的 Json 配置文件
【发布时间】:2019-08-04 01:53:45
【问题描述】:

我有以下 mongodb 的 JSON 配置文件(名为 mongoConfig.json):

{
    "mongodb": {
      "host": "localhost",
      "port": 27017,
      "database": "test"
    }
  }

我正在尝试使用此文件连接到我的数据库。到目前为止,我尝试过这样使用它:

//mongoConn.ts

'use strict';

const mongoose = require('mongoose');
var config = require('./../mongoConfig.json');

exports.connect = () => {
  return mongoose.connect(config.toString())
    .then(() => {     
      console.log("Successfully connected to database!");
      return mongoose.connection; });
};

但我遇到了错误:UnhandledPromiseRejectionWarning: Error: Invalid schema, expected `mongodb` or `mongodb+srv`

我的文件夹结构是:

        |-.vs
        |-node_modules
        |-src
        |   └── connections
        |           └──mongoConn.ts
        |   └── mongoConfig.json

我是使用 mongoDB 和配置文件的初学者,所以我猜我也没有正确使用 JSON 文件...

任何帮助将不胜感激! :)

编辑:更正了路径! (从'./mongoConfig.json''./../mongoConfig.json'

【问题讨论】:

  • 分享你的文件夹结构
  • 尝试制作mongoConfig .js 文件并在文件中导出/默认导出
  • @mehta-rohan 更新了问题
  • @fard 不幸的是,要求之一是 mongoConfig 文件的类型为 JSON :(
  • @user3063909 基于文件树你应该做./../mongoConfig.json

标签: json mongodb typescript mongoose


【解决方案1】:

Mongooes.connect 接受 uri 字符串:mongodb://username:password@host:port/database。所以试试吧,

mongoose.connect('mongodb://username:password@host:port/database?options...');

mongoose.connect('mongodb://username:password@host:port/database', options, function(error) {
  // Check error in initial connection. There is no 2nd param to the callback.
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多