Fri*_*iso 3 mongodb node.js typescript
我在 Node.js 服务器上工作,连接到 MongoDB 并用 TypeScript 编写。当我尝试使用 MongoDB 时,它不会创建连接,但是当我检查 mongo 输出时,它似乎确实创建了连接。
我在代码中缺少什么来定义 Node.js 中的连接?
我的连接字符串是 'mongodb://localhost:27017'
我的连接方法:
connect() {
console.log('connecting to mongo') //this is called
MongoClient.connect(this.connectionString, {useNewUrlParser: true})
.then(client => {
console.log('setting client'); //this doesn't get called
this.client = client;
console.log(this.client);
})
.catch(error => {
console.log('error during connecting to mongo: '); //this also doesn't get called
console.error(error);
});
}
Run Code Online (Sandbox Code Playgroud)
蒙戈输出:
2018-11-08T23:06:24.106+0100 I NETWORK [listener] 连接从 127.0.0.1:51345 #11 接受(现在打开 2 个连接)
2018-11-08T23:06:24.107+0100 I NETWORK [conn11] 从 127.0.0.1:51345 conn11: { driver: { name: "nodejs", version: "3.1.9" }, os: { type :“达尔文”,名称:“达尔文”,架构:“x64”,版本:“17.7.0”},平台:“Node.js v8.9.3,LE,mongodb-core:3.1.8”}
我的存储库位于https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/db/mongo.db.ts以获得完整代码。
console.log(db) 正如 shkaper 所问
MongoClient {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ url: 'mongodb://localhost:27017',
options:
{ servers: [Array],
caseTranslate: true,
useNewUrlParser: true,
socketTimeoutMS: 360000,
connectTimeoutMS: 30000,
promiseLibrary: [Function: Promise] },
promiseLibrary: [Function: Promise],
dbCache: {},
sessions: [] },
topology:
Server {
domain: null,
_events:
{ serverOpening: [Function],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
commandStarted: [Function],
commandSucceeded: [Function],
commandFailed: [Function],
joined: [Function],
left: [Function],
ping: [Function],
ha: [Function],
authenticated: [Function],
error: [Function],
timeout: [Function],
close: [Function],
parseError: [Function],
open: [Object],
fullsetup: [Object],
all: [Object],
reconnect: [Function] },
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v8.9.3, LE' },
s:
{ coreTopology: [Object],
sCapabilities: null,
clonedOptions: [Object],
reconnect: true,
emitError: true,
poolSize: 5,
storeOptions: [Object],
store: [Object],
host: 'localhost',
port: 27017,
options: [Object],
sessionPool: [Object],
sessions: [],
promiseLibrary: [Function: Promise] } } }
Run Code Online (Sandbox Code Playgroud)
问题是因为mongo.connect异步代码和控制器错误地调用了它。所以后续行将mongo.getDb()在没有this.client正确启动的情况下执行。
由于您使用 Typescript,我们可以使用async/await更干净的代码。
async connect() { // add async
console.log('connecting to mongo');
try {
if (!this.client) { // I added this extra check
console.log('setting client');
this.client = await MongoClient.connect(this.connectionString, { useNewUrlParser: true })
console.log(this.client);
}
} catch(error) {
console.log('error during connecting to mongo: ');
console.error(error);
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器代码中
async get(req: Request, res: Response) { // add async
const mongo = new MongoDb();
await mongo.connect(); // add await
const db = mongo.db();
// ....
}
Run Code Online (Sandbox Code Playgroud)
我用更改尝试了你的 repo 并得到了这个回复
希望能帮助到你
| 归档时间: |
|
| 查看次数: |
13037 次 |
| 最近记录: |