0

So what I'm doing here is at first joining some lobby by password:

app.post('/join-lobby', async(req, res) => {});

And then below the code I'm declaring my socket emit:

socket.on('join-lobby', (data) => {
    User.findOne({username: data.username}).then(async(user) => {
        if(user != null) {
            let memberofLobby = await UserLobby.findOne({username: user.username}); // RETURNS NULL
            //let lobbyId = await memberofLobby.lobby_id;
            console.log(memberofLobby);
            io.emit('join-lobby', {
                username: user.username,
                level: user.level,
                skin: user.skin,
                lobbyId: memberofLobby.lobby_id
            });
            //let lobbyId = memberofLobby.lobby_id;
        } else {
            console.log('User not found');
        }
    })
});

Problem is that I cannot get at the same time data from DB collection in my socket let memberofLobby = await UserLobby.findOne({username: user.username}); at this line. So it returns me NULL.

When I submit form (type in password) the socket emit is immediately fired on form submit and I believe that's why it can pick up the information from collection.

P.S. User is added perfectly after page refresh so the POST (the first route) works fine.

$( "#join-lobby" ).submit(function( event ) {
    socket.emit('join-lobby', {
        username: $("#username").text()
    });
});
-------------------------------------
app.post('/join-lobby', async(req, res) => {});
-------------------------------------
    socket.on('join-lobby', (data) => {
        User.findOne({username: data.username}).then(async(user) => {
            if(user != null) {
                let memberofLobby = await UserLobby.findOne({username: user.username}); // NULL
zlotte
  • 221
  • 1
  • 11

1 Answers1

0

Mongoose docs says that the findOne() method returns a "query" object. So, in the following line you're trying to await a method which does not return promise:

let memberofLobby = await UserLobby.findOne({username: user.username});

I suggest adding .exec() at the end of the line, to actually execute the findOne() and get a promise as a result, like this.

let memberofLobby = await UserLobby.findOne({username: user.username}).exec();

Let me know if it worked for you!

Nico
  • 179
  • 1
  • 7