# Mongodb api and node red

**URL:** <https://discourse.nodered.org/t/mongodb-api-and-node-red/21857>\
**Category:** General\
**Created:** [17 February 2020 13:36 UTC](https://discourse.nodered.org/t/mongodb-api-and-node-red/21857 "2020-02-17T13:36:19Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![tobias](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/tobias/32/17195_2.png) [@tobias](https://discourse.nodered.org/u/tobias)\
**Post date:** [17 February 2020 13:36 UTC](https://discourse.nodered.org/t/mongodb-api-and-node-red/21857/1 "2020-02-17T13:36:19Z")

</div>

Hello,

```auto
msg.topic = "Initialization of db";

var MongoClient = global.get('mongodb').MongoClient;
var Server = global.get('mongodb').Server;

var db;
  
try {
   new MongoClient(new Server('localhost', 27017), {
    user: 'node_red_admin',
    password: ':)',
    authSource: 'node_red_db1'}).connect((err, client) => {
        
        if(err) {
            console.error(err);
            msg.errClientCon = err;
        }
        
        db = client.db('node_red_db1');
        
        db.dropCollection('twitter').catch(err => {
            if(err) console.error("ERR: " + err);
        });
        
        db.createCollection('twitter', {capped: true, size: 500000, max: 100}, (err, col) => {
            if(err) console.error("ERR: " + err);
        });

  });
} catch(ex) {
    msg.errEx = ex.message;
}

return msg;

```

This works fine.

```auto
msg.topic = "Initialization of db";

var MongoClient = global.get('mongodb').MongoClient;
var Server = global.get('mongodb').Server;

var mongoc;
var db;
  
try {
   new MongoClient(new Server('localhost', 27017), {
    user: 'node_red_admin',
    password: ':(',
    authSource: 'node_red_db1'}).connect((err, client) => {
        mongoc = client;
    });
   
    var mongoc = global.get('mongoc');
    db = mongoc.db('node_red_db1');

    db.dropCollection('twitter').catch(err => {
        if (err) console.error("ERR: " + err);
    });

    db.createCollection('twitter', { capped: true, size: 500000, max: 100 }, (err, col) => {
        if (err) console.error("ERR: " + err);
    });

} catch(ex) {
    msg.errEx = ex.message;
}

return msg;

```

This doesn't. But i cann't explain why, anybody else?  
The error message is: "Cannot read property 'db' of undefined".

My intention is to store the `client` in the global context to use it in other nodes as well, but when it's not even possible to store it in a local variable (`mongoc` in my case) it will not be possible.

Best regards, Tobias

---

<div class="post-metadata">

**Author:** ![afelix](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/afelix/32/9743_2.png) [@afelix](https://discourse.nodered.org/u/afelix)\
**Post date:** [17 February 2020 13:57 UTC](https://discourse.nodered.org/t/mongodb-api-and-node-red/21857/2 "2020-02-17T13:57:01Z")

</div>

Because the connect function is resolved asynchronously, meaning that the line calling `mongoc.db` can run before mongoc is actually populated.  
Another tip, even though you’re connecting to a mongo server on localhost, but change your password and remove it from the post above.

---

<div class="post-metadata">

**Author:** ![tobias](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/tobias/32/17195_2.png) [@tobias](https://discourse.nodered.org/u/tobias)\
**Post date:** [17 February 2020 14:05 UTC](https://discourse.nodered.org/t/mongodb-api-and-node-red/21857/3 "2020-02-17T14:05:52Z")

</div>

Okay, thank you....when i try to use `await` node red allways displays errors:  
"SyntaxError: await is only valid in async function". That's why i thought it is synchronous.  
Thanks, i thought about it before i posted it, but it will never be production system.

---

<div class="post-metadata">

**Author:** ![afelix](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/afelix/32/9743_2.png) [@afelix](https://discourse.nodered.org/u/afelix)\
**Post date:** [17 February 2020 18:23 UTC](https://discourse.nodered.org/t/mongodb-api-and-node-red/21857/4 "2020-02-17T18:23:56Z")

</div>

The outer function node code is synchronous, but capable of handling async code the same way you would do when writing ES6 compatible code yourself. Meaning you can use `await`, but it has to be inside an `async function`. Which in term can be run either with promises or callbacks. In order to output from the function node asynchronously, check the docs: [https://nodered.org/docs/user-guide/writing-functions](https://nodered.org/docs/user-guide/writing-functions)

See further this topic which has an example of async function calls in a function node: [Async function - getting error: TypeError: is not a constructor](https://discourse.nodered.org/t/async-function-getting-error-typeerror-is-not-a-constructor/13259)

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [2 March 2020 18:23 UTC](https://discourse.nodered.org/t/mongodb-api-and-node-red/21857/5 "2020-03-02T18:23:58Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
