在针对本地mongoDB数据库成功测试了我的Node应用程序之后,我现在尝试连接到我们的服务器数据库-与我的本地mongoDB不同,该数据库受用户和密码保护。
尝试连接服务器时遇到问题。具体来说,我收到此错误:
MongoError:必须先连接MongoClient才能调用 MongoClient.prototype.db
我正在尝试的信誉看起来像这样:
{
"MONGO_URL": "mongodb://myuser:mypassword@someurl.com:27017?authSource=admin",
"MONGO_DATABASE": "bta",
"MONGO_COLLECTION": "jobs"
}
这是我的连接代码:
const config = require('./configuration');
const url = config.get('MONGO_URL');
const dbName = config.get('MONGO_DATABASE');
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(url);
async function getJobDetails() {
client.connect(async function () {
try {
const db = await client.db(dbName);
// do stuff
});
} catch (error) {
console.log(error);
}
});
}
我在这里想念什么?
答案 0 :(得分:0)
尝试:
const mongoClient = require('mongodb').MongoClient;
mongoClient.connect(url, { useNewUrlParser: true }, function(client_err, client) {
if (client != null) {
var client_db = client.db(dbName);
}
client.close();
});
答案 1 :(得分:0)
作为MongoDB。 https://mongodb.github.io/node-mongodb-native/3.2/tutorials/connect/
并且请尝试仔细检查服务器上的数据库是否配置正确。
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL with password example
const url = 'mongodb://user:password@address:27017?readPreference=primary&authSource=admin';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
这对两个有效的本地主机/服务器网址都有效
答案 2 :(得分:0)
我弄清楚了问题所在,并且能够将其连接起来。问题在于该站点是安全的,因此我不得不在URL连接字符串中添加MERGE dbo.VipAbonentai vip
USING (SELECT ab.abonentoID From Abonentas as ab
Inner join Asmuo as A on ab.asmensID = A.asmensID
Inner join Miestas as M on M.miestoID = M.miestoID
Where M.miestoID = 1)
WHEN MATCHED
THEN UPDATE SET
vip.abonentoID = ab.abonentoID,
WHEN NOT MATCHED BY TARGET
THEN
INSERT (AbonentoID, asmensID, planoID, numeris, sutartiesPradzia,
sutartiesPabaiga)
VALUES (ab.AbonentoID, ab.asmensID, ab.planoID, ab.numeris,
ab.sutartiesPradzia, ab.SutartiesPabaiga) ;
:
ssl=true