How to connect to MongoDB using Node.js written in TypeScript?









up vote
0
down vote

favorite












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.



What am I missing in my code to define the connection in Node.js?



My connection string is 'mongodb://localhost:27017'



My connection method:



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 output:




2018-11-08T23:06:24.106+0100 I NETWORK [listener] connection accepted from 127.0.0.1:51345 #11 (2 connections now open)



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"




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) 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]









share|improve this question























  • can we see the console output from your application?
    – Jim B.
    Nov 12 at 4:49










  • Doesn't seems a problem with the code, Are you trying to connect to remote mongodb hosted on another server?
    – Suresh Prajapati
    Nov 12 at 5:34










  • Add a line with console.log(db) after this line: github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/… and share the output please
    – shkaper
    Nov 12 at 14:20










  • @shkaper I added the output
    – Friso
    Nov 12 at 20:09










  • @SureshPrajapati I'm trying to connect to localhost, I added the connection string I'm using
    – Friso
    Nov 12 at 20:09














up vote
0
down vote

favorite












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.



What am I missing in my code to define the connection in Node.js?



My connection string is 'mongodb://localhost:27017'



My connection method:



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 output:




2018-11-08T23:06:24.106+0100 I NETWORK [listener] connection accepted from 127.0.0.1:51345 #11 (2 connections now open)



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"




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) 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]









share|improve this question























  • can we see the console output from your application?
    – Jim B.
    Nov 12 at 4:49










  • Doesn't seems a problem with the code, Are you trying to connect to remote mongodb hosted on another server?
    – Suresh Prajapati
    Nov 12 at 5:34










  • Add a line with console.log(db) after this line: github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/… and share the output please
    – shkaper
    Nov 12 at 14:20










  • @shkaper I added the output
    – Friso
    Nov 12 at 20:09










  • @SureshPrajapati I'm trying to connect to localhost, I added the connection string I'm using
    – Friso
    Nov 12 at 20:09












up vote
0
down vote

favorite









up vote
0
down vote

favorite











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.



What am I missing in my code to define the connection in Node.js?



My connection string is 'mongodb://localhost:27017'



My connection method:



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 output:




2018-11-08T23:06:24.106+0100 I NETWORK [listener] connection accepted from 127.0.0.1:51345 #11 (2 connections now open)



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"




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) 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]









share|improve this question















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.



What am I missing in my code to define the connection in Node.js?



My connection string is 'mongodb://localhost:27017'



My connection method:



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 output:




2018-11-08T23:06:24.106+0100 I NETWORK [listener] connection accepted from 127.0.0.1:51345 #11 (2 connections now open)



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"




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) 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]






node.js mongodb typescript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 at 20:08

























asked Nov 8 at 22:08









Friso

64811341




64811341











  • can we see the console output from your application?
    – Jim B.
    Nov 12 at 4:49










  • Doesn't seems a problem with the code, Are you trying to connect to remote mongodb hosted on another server?
    – Suresh Prajapati
    Nov 12 at 5:34










  • Add a line with console.log(db) after this line: github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/… and share the output please
    – shkaper
    Nov 12 at 14:20










  • @shkaper I added the output
    – Friso
    Nov 12 at 20:09










  • @SureshPrajapati I'm trying to connect to localhost, I added the connection string I'm using
    – Friso
    Nov 12 at 20:09
















  • can we see the console output from your application?
    – Jim B.
    Nov 12 at 4:49










  • Doesn't seems a problem with the code, Are you trying to connect to remote mongodb hosted on another server?
    – Suresh Prajapati
    Nov 12 at 5:34










  • Add a line with console.log(db) after this line: github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/… and share the output please
    – shkaper
    Nov 12 at 14:20










  • @shkaper I added the output
    – Friso
    Nov 12 at 20:09










  • @SureshPrajapati I'm trying to connect to localhost, I added the connection string I'm using
    – Friso
    Nov 12 at 20:09















can we see the console output from your application?
– Jim B.
Nov 12 at 4:49




can we see the console output from your application?
– Jim B.
Nov 12 at 4:49












Doesn't seems a problem with the code, Are you trying to connect to remote mongodb hosted on another server?
– Suresh Prajapati
Nov 12 at 5:34




Doesn't seems a problem with the code, Are you trying to connect to remote mongodb hosted on another server?
– Suresh Prajapati
Nov 12 at 5:34












Add a line with console.log(db) after this line: github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/… and share the output please
– shkaper
Nov 12 at 14:20




Add a line with console.log(db) after this line: github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/… and share the output please
– shkaper
Nov 12 at 14:20












@shkaper I added the output
– Friso
Nov 12 at 20:09




@shkaper I added the output
– Friso
Nov 12 at 20:09












@SureshPrajapati I'm trying to connect to localhost, I added the connection string I'm using
– Friso
Nov 12 at 20:09




@SureshPrajapati I'm trying to connect to localhost, I added the connection string I'm using
– Friso
Nov 12 at 20:09












2 Answers
2






active

oldest

votes

















up vote
1
down vote



accepted
+50










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.



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




And in controller code



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



I tried your repo with the changes and got this response



enter image description here



Hope it helps






share|improve this answer





























    up vote
    1
    down vote













    Based on what you said about neither error nor success callbacks being called, I think the problem is not only in code here: https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/db/mongo.db.ts
    But also e.g. here: https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/controllers/to-do.controller.ts
    When you run mongo.connect there should be an option to wait for the promise returned from MongoClient.connect. So I would change code in mongo.db.ts to for example sth like this (it depends how you want to handle this promise):



    connect() 
    console.log('connecting to mongo')
    return MongoClient.connect(this.connectionString, useNewUrlParser: true)
    .then(client =>
    console.log('setting client');
    this.client = client;
    console.log(this.client);
    )
    .catch(error =>
    console.log('error during connecting to mongo: ');
    console.error(error);
    );



    Then in to-do.controller.ts you can await this or use then:



    get(req: Request, res: Response) 
    const mongo = new MongoDb();
    mongo.connect().then(() =>

    const db = mongo.getDb();
    const collection = db.collection('todo', (error, collection) =>
    if (error)
    res.json(error);
    res.statusCode = HttpStatus.BAD_REQUEST
    return;


    collection.find().toArray((error, result) =>
    if (error)
    res.json(error);
    res.statusCode = HttpStatus.BAD_REQUEST


    res.json(result);
    res.statusCode = HttpStatus.OK;
    )

    );

    mongo.close();
    );



    I suppose that your code just does not "wait" for connection to be established and then fails.






    share|improve this answer




















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53216884%2fhow-to-connect-to-mongodb-using-node-js-written-in-typescript%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote



      accepted
      +50










      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.



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




      And in controller code



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



      I tried your repo with the changes and got this response



      enter image description here



      Hope it helps






      share|improve this answer


























        up vote
        1
        down vote



        accepted
        +50










        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.



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




        And in controller code



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



        I tried your repo with the changes and got this response



        enter image description here



        Hope it helps






        share|improve this answer
























          up vote
          1
          down vote



          accepted
          +50







          up vote
          1
          down vote



          accepted
          +50




          +50




          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.



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




          And in controller code



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



          I tried your repo with the changes and got this response



          enter image description here



          Hope it helps






          share|improve this answer














          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.



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




          And in controller code



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



          I tried your repo with the changes and got this response



          enter image description here



          Hope it helps







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 12 at 21:00

























          answered Nov 12 at 20:43









          deerawan

          2,23531424




          2,23531424






















              up vote
              1
              down vote













              Based on what you said about neither error nor success callbacks being called, I think the problem is not only in code here: https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/db/mongo.db.ts
              But also e.g. here: https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/controllers/to-do.controller.ts
              When you run mongo.connect there should be an option to wait for the promise returned from MongoClient.connect. So I would change code in mongo.db.ts to for example sth like this (it depends how you want to handle this promise):



              connect() 
              console.log('connecting to mongo')
              return MongoClient.connect(this.connectionString, useNewUrlParser: true)
              .then(client =>
              console.log('setting client');
              this.client = client;
              console.log(this.client);
              )
              .catch(error =>
              console.log('error during connecting to mongo: ');
              console.error(error);
              );



              Then in to-do.controller.ts you can await this or use then:



              get(req: Request, res: Response) 
              const mongo = new MongoDb();
              mongo.connect().then(() =>

              const db = mongo.getDb();
              const collection = db.collection('todo', (error, collection) =>
              if (error)
              res.json(error);
              res.statusCode = HttpStatus.BAD_REQUEST
              return;


              collection.find().toArray((error, result) =>
              if (error)
              res.json(error);
              res.statusCode = HttpStatus.BAD_REQUEST


              res.json(result);
              res.statusCode = HttpStatus.OK;
              )

              );

              mongo.close();
              );



              I suppose that your code just does not "wait" for connection to be established and then fails.






              share|improve this answer
























                up vote
                1
                down vote













                Based on what you said about neither error nor success callbacks being called, I think the problem is not only in code here: https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/db/mongo.db.ts
                But also e.g. here: https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/controllers/to-do.controller.ts
                When you run mongo.connect there should be an option to wait for the promise returned from MongoClient.connect. So I would change code in mongo.db.ts to for example sth like this (it depends how you want to handle this promise):



                connect() 
                console.log('connecting to mongo')
                return MongoClient.connect(this.connectionString, useNewUrlParser: true)
                .then(client =>
                console.log('setting client');
                this.client = client;
                console.log(this.client);
                )
                .catch(error =>
                console.log('error during connecting to mongo: ');
                console.error(error);
                );



                Then in to-do.controller.ts you can await this or use then:



                get(req: Request, res: Response) 
                const mongo = new MongoDb();
                mongo.connect().then(() =>

                const db = mongo.getDb();
                const collection = db.collection('todo', (error, collection) =>
                if (error)
                res.json(error);
                res.statusCode = HttpStatus.BAD_REQUEST
                return;


                collection.find().toArray((error, result) =>
                if (error)
                res.json(error);
                res.statusCode = HttpStatus.BAD_REQUEST


                res.json(result);
                res.statusCode = HttpStatus.OK;
                )

                );

                mongo.close();
                );



                I suppose that your code just does not "wait" for connection to be established and then fails.






                share|improve this answer






















                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  Based on what you said about neither error nor success callbacks being called, I think the problem is not only in code here: https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/db/mongo.db.ts
                  But also e.g. here: https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/controllers/to-do.controller.ts
                  When you run mongo.connect there should be an option to wait for the promise returned from MongoClient.connect. So I would change code in mongo.db.ts to for example sth like this (it depends how you want to handle this promise):



                  connect() 
                  console.log('connecting to mongo')
                  return MongoClient.connect(this.connectionString, useNewUrlParser: true)
                  .then(client =>
                  console.log('setting client');
                  this.client = client;
                  console.log(this.client);
                  )
                  .catch(error =>
                  console.log('error during connecting to mongo: ');
                  console.error(error);
                  );



                  Then in to-do.controller.ts you can await this or use then:



                  get(req: Request, res: Response) 
                  const mongo = new MongoDb();
                  mongo.connect().then(() =>

                  const db = mongo.getDb();
                  const collection = db.collection('todo', (error, collection) =>
                  if (error)
                  res.json(error);
                  res.statusCode = HttpStatus.BAD_REQUEST
                  return;


                  collection.find().toArray((error, result) =>
                  if (error)
                  res.json(error);
                  res.statusCode = HttpStatus.BAD_REQUEST


                  res.json(result);
                  res.statusCode = HttpStatus.OK;
                  )

                  );

                  mongo.close();
                  );



                  I suppose that your code just does not "wait" for connection to be established and then fails.






                  share|improve this answer












                  Based on what you said about neither error nor success callbacks being called, I think the problem is not only in code here: https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/db/mongo.db.ts
                  But also e.g. here: https://github.com/FrisoDenijs/MEAN-ToDo/blob/master/server/src/controllers/to-do.controller.ts
                  When you run mongo.connect there should be an option to wait for the promise returned from MongoClient.connect. So I would change code in mongo.db.ts to for example sth like this (it depends how you want to handle this promise):



                  connect() 
                  console.log('connecting to mongo')
                  return MongoClient.connect(this.connectionString, useNewUrlParser: true)
                  .then(client =>
                  console.log('setting client');
                  this.client = client;
                  console.log(this.client);
                  )
                  .catch(error =>
                  console.log('error during connecting to mongo: ');
                  console.error(error);
                  );



                  Then in to-do.controller.ts you can await this or use then:



                  get(req: Request, res: Response) 
                  const mongo = new MongoDb();
                  mongo.connect().then(() =>

                  const db = mongo.getDb();
                  const collection = db.collection('todo', (error, collection) =>
                  if (error)
                  res.json(error);
                  res.statusCode = HttpStatus.BAD_REQUEST
                  return;


                  collection.find().toArray((error, result) =>
                  if (error)
                  res.json(error);
                  res.statusCode = HttpStatus.BAD_REQUEST


                  res.json(result);
                  res.statusCode = HttpStatus.OK;
                  )

                  );

                  mongo.close();
                  );



                  I suppose that your code just does not "wait" for connection to be established and then fails.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 12 at 20:31









                  barnski

                  618411




                  618411



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53216884%2fhow-to-connect-to-mongodb-using-node-js-written-in-typescript%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

                      Crossroads (UK TV series)

                      ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế