mongoose – Node.js function calls parts of code twice

I’m learning Node and can’t quite wrap my head around what is happening here. This function is suppose to create a chat room document in MongoDB if the room name doesn’t already exist.

const mongoose = require('mongoose');
const Chat = require("../Models/Chat");


async function CreateRoom(req, res) {
    const { room, username, _id } = req.body;
    console.log(`CHAT: createRoom ${room}`);

    const chat = await Chat.findOne({ "room": room }).exec();
    console.log(`____x`)    
    if (chat) {
        console.log(`____0`)
        res.sendStatus(409); // Conflict        
    }
console.log(`____1`)
    const result = await Chat.create({
        room: room,
        message: [
            {
                text: "Room created",
                from: _id,
            }
        ]
    });
    console.log("____2")    
    if (!result) {
        console.log(`CHAT: createRoom ${room} failed`);
        res.sendStatus(400);
    }
    console.log("____3")
    console.log(`CHAT room created: ${room}`);
    return res.sendStatus(201);
}

module.exports = { CreateRoom };

The output looks like this:

CHAT: createRoom lobby
____x
____1
____x
____1
____2
____3
CHAT room created: lobby
____2
____3
CHAT room created: lobby

I’m completely baffled at how the “____x” shows up twice, as well as the other duplicates. Can anyone enlighten me on how this is possible? Thanks.

Read more here: Source link