JJNL77
JJNL77

Reputation: 159

mongoDB getting 'undefined' by find

I want to use all values that

bericht.find({
        room: room
      }).toArray(function(err, docs) {
        assert.equal(err, null);
        str2 = str2 + docs.message;

This function can find, the only problem is I keep getting 'undefined'. But I want to use the value's and socket.emit the value's to the client size so all messages can be used there. Can anybody help me? How I can do this.

const url = 'mongodb://localhost:27017';

io.on('connection', (socket) => {

    var str2 = [];

    // Database Name
    const dbName = 'chatapplication';


    const findMessageFromRoom = function(room, db, callback) {
      // Get the messages from certain room
      const bericht = db.collection('Bericht');
      // Find some documents
      bericht.find({
        room: room
      }).toArray(function(err, docs) {
        assert.equal(err, null);
        str2 = str2 + docs.message;
        // callback(docs);
      });
      console.log(str2);
      socket.emit('test1', str2);
    };

    function getAllMessagesInRoom(room) {
      MongoClient.connect(url, function(err, client) {
        assert.equal(null, err);
        console.log("Connected successfully to server");

        const db = client.db(dbName);

        findMessageFromRoom(room, db, function() {
          client.close();
        });

      });
    }

  )
};

Upvotes: 2

Views: 134

Answers (1)

Tamas Szoke
Tamas Szoke

Reputation: 5542

Node.js is asynchronous, it won't wait for the database query to finish, just logs the str2 variable immediately. It's not defined at that time, so you get 'undefined' message on console.

Use it like this:

bericht.find({
    room: room
}).toArray(function(err, docs) {
    assert.equal(err, null);
    str2 = str2 + docs.message;
    // callback(docs);

    console.log(str2);
    socket.emit('test1', str2);
});

Upvotes: 1

Related Questions