我有以下用于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'
)
答案 0 :(得分:0)
Mongooes.connect将uri字符串放入mongodb://username:password@host:port/database
中。所以尝试,
mongoose.connect('mongodb://username:password@host:port/database?options...');
OR
mongoose.connect('mongodb://username:password@host:port/database', options, function(error) {
// Check error in initial connection. There is no 2nd param to the callback.
});