0

Similar question has been asked many times. But i just cant figure it out. Solving this issue literally whole day. Basically, what i understood from the diffrent answers, the error means that im loading my model into the application before the mongoose connection is made. I resolved this, but its still not working.. anyone has any idea?

-- this is the index.ts file

  .connect(mongoDBURL)
  .then(() => {
    console.log("Connecting to telegram...");
    const bot = new Telegraf(telegramConnection.token);
    addProperties(bot, mongo);
    bot.launch();
    console.log("bot is ready");
  })
  .catch((err) => {
    console.log(err);
  });

-- user.ts

  bot.hears("/register", (ctx) => {
    MasterController()
      .userController(mongo)
      .createUser(ctx.message.chat.id, "random_user");
  });

-- the createUser function

  const createUser = async (_chatId: Number, _username: string) => {
    console.log(`chatID = ${_chatId}`);

    const user = new UserModel({
      chatId: _chatId,
      username: _username,
    });
    await user
      .save()
      .then((res) => {
        console.log("User registered");
      })
      .catch((err) => {
        console.log(err);
      });
  };
  • Yes, you understood it right. "I resolved this" - how do you know? The snippets of the code you posted are not sufficient to make such conclusion. If you check the answers, there are 2 most common issues - not waiting for connect() to resolve, or not able to establish connection on network level. Mongoose defers actual connection and buffer all queries until the connection is actually established. – Alex Blex Jun 27 '22 at 13:22
  • yea, my bad, resolve this is not the right word. I meant i tried to, and basically putted rest of the code into the then. which i believe should execute only after successfull connection to the database. For the other option there is the catch. So what would u recommend me please? – Štěpán Karlovec Jun 27 '22 at 13:40
  • "putt rest of the code into the then." - that's exactly the missing part of the index.ts. You cut the head of the promise chain which makes it hard to assert whether you put it in the right place. no all "then" are equal, and as I said, Mongoose resolves the promise before actual connection is established, so please confirm the database is reachable from the application. – Alex Blex Jun 27 '22 at 14:20

0 Answers0