Pritt Balagopal
Pritt Balagopal

Reputation: 1342

I get a "Cannot read property 'list' of undefined" while using MongoDB

I'm coding a Discord Bot that uses MongoDB as a database for custom commands and custom reactions. This is a problem that is bothering me for a while. What's strange is that this problem occurs sometimes, and not at other times. Basically, I have my code as:

const MongoClient = require('mongodb').MongoClient;
var db;
var cc;
var reactions;

MongoClient.connect('mongodb://<username>:<password>@ds020218.mlab.com:20218/zilla-bot-gamma', { useNewUrlParser: true }, (err, client) => {
    if(err) console.log(err);
    console.log('Connected to database!');
    db = client.db('zilla-bot-gamma');

    db.collection('cc').find().toArray((err, results) => {
        if(err) console.log(err);
        cc = results[0];
    });

    db.collection('reactions').find().toArray((err, results) =>  {
        if(err) console.log(err);
        reactions = results[0];
    });
});

exports.reactEmoji = function(messageContent) {
    var reactEmojicontents = [];
    var j=0;
    for(var i=0; i<reactions.list.length; i++) {
        if(messageContent.toLowerCase().indexOf(reactions.list[i].trigger) >= 0) {
            reactEmojicontents[j] = reactions.list[i].output;
            j++;
        }
    }

    if(reactEmojicontents[0]) {
        return reactEmojicontents;
    }

    return 'None';
}

My database collection named reactions would be:

{
    "_id": {
        "$oid": "hidden"
    },
    "list": [
        {
            "trigger": "jason",
            "output": "407194701515587584"
        },
        {
            "trigger": "nitro",
            "output": "476637660417359872"
        },
        {
            "trigger": "pritt",
            "output": "🍍"
        },
        {
            "trigger": "kappa",
            "output": "392389534064574473"
        },
        {
            "trigger": "zilla",
            "output": "392389485578420224"
        },
        {
            "trigger": "tamz",
            "output": "392363229906599948"
        },
        {
            "trigger": "hello",
            "output": "484051886677426176"
        },
        {
            "trigger": "node",
            "output": "484966646029484033"
        },
        {
            "trigger": "heroku",
            "output": "485798141791043584"
        },
        {
            "trigger": "even",
            "output": "486235385098403847"
        }
    ]
}

Upon running this script, I get the following message on my cmd:

Connected to database!
C:\JSFolder\ZillaBotGamma\Messages\msghandle.js:332
    for(var i=0; i<reactions.list.length; i++) {
                             ^

TypeError: Cannot read property 'list' of undefined
at exports.reactEmoji (C:\JSFolder\ZillaBotGamma\Messages\msghandle.js:332:30)
at Client.bot.on (C:\JSFolder\ZillaBotGamma\main.js:228:24)
at Client.emit (events.js:159:13)
at MessageCreateHandler.handle (C:\JSFolder\ZillaBotGamma\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (C:\JSFolder\ZillaBotGamma\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (C:\JSFolder\ZillaBotGamma\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (C:\JSFolder\ZillaBotGamma\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (C:\JSFolder\ZillaBotGamma\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:159:13)
at Receiver._receiver.onmessage (C:\JSFolder\ZillaBotGamma\node_modules\ws\lib\websocket.js:137:47)

I find this to be very strange. The reactions.list is clearly defined as an array in the database, and this error message pops up after showing "Connected to database!". I then figured it would be because of the async nature of the callbacks in db.collection().get(), so I had tried defining the callback as async and putting an reactions = await results[0]. That didn't cut it.

Can anyone tell me what's going on?

Some additional info:

  1. I'm also hosting a website for my bot using express in the same directory.

Upvotes: 0

Views: 564

Answers (1)

Noel Kriegler
Noel Kriegler

Reputation: 529

Reactions is being populated by this call.

  db.collection('reactions').find().toArray((err, results) =>  {
        if(err) console.log(err);
        reactions = results[0];
    });

If for some reason this call fails or is not complete before your reactEmoji method is called then you will get an error.

You should make sure reactions has a value set before trying to access a property on it.

if(Boolean(reactions)) {
   for(var i=0; i<reactions.list.length; i++) {
        if(messageContent.toLowerCase().indexOf(reactions.list[i].trigger) >= 0) {
            reactEmojicontents[j] = reactions.list[i].output;
            j++;
        }
    }
} 

You could then populate the list and recall the method. I would personally create a method called getReactions() that returns a promise or uses a callback to use if reactions is not set.

EDIT: something like this

  async function getReactions() {
   return new Promise(function (resolve, reject){
     db.collection('reactions').find().toArray((err, results) =>  {
        if(err) reject(err.message);
        resolve(results[0]);
     });
   });
  }

you could then call it like.

let reactions = await getReactions();

Upvotes: 2

Related Questions