本文介绍了如何使用用TypeScript编写的Node.js连接到MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Node.js服务器,它连接到MongoDB并使用TypeScript编写.当我尝试使用MongoDB时,它不会创建连接,但是当我检查mongo输出时,它的确会创建连接.

I'm working on a Node.js server, connecting to MongoDB and written with TypeScript. When I try to use MongoDB it doesn't create a connection, however when I check the mongo output it does appear to create a connection.

在Node.js中定义连接时,我在代码中缺少什么?

What am I missing in my code to define the connection in 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);
    });
}

Mongo输出:

2018-11-08T23:06:24.107 + 0100我网络[conn11]从127.0.0.1:51345 conn11接收了客户端元数据:{驱动程序:{名称:"nodejs",版本:"3.1.9"},操作系统:{类型:"Darwin",名称:"darwin",体系结构:"x64",版本:"17.7.0"},平台:"Node.js v8.9.3,LE,mongodb-core:3.1.8"}

2018-11-08T23:06:24.107+0100 I NETWORK [conn11] received client metadata from 127.0.0.1:51345 conn11: { driver: { name: "nodejs", version: "3.1.9" }, os: { type: "Darwin", name: "darwin", architecture: "x64", version: "17.7.0" }, platform: "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 获取完整代码.

My repository is at https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/db/mongo.db.ts for the full code.

console.log(db)

console.log(db) as asked by 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] } } }

推荐答案

问题是因为mongo.connect是异步代码,并且控制器错误地调用它.因此后续的mongo.getDb()行将在没有正确启动this.client的情况下执行.

The issue is because mongo.connect is async code and controller call it wrongly. so the subsequent line mongo.getDb() will be executed without having this.client initiated properly.

由于您使用的是Typescript,因此我们可以使用async/await来获得更简洁的代码.

Since you use Typescript, we can use async/await for cleaner code.

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);
    }
}

并在控制器代码中

async get(req: Request, res: Response) { // add async
  const mongo = new MongoDb();
  await mongo.connect(); // add await
  const db = mongo.db();
  // ....
}

我尝试了您的回购并进行了更改

I tried your repo with the changes and got this response

希望有帮助

这篇关于如何使用用TypeScript编写的Node.js连接到MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 12:45