在数据库加载并执行查询后编辑现有消息,discord.js

问题描述 投票:0回答:0

这是我正在尝试做的事情:

  1. 连接到 MongoDB。
  2. 执行查找查询。
  3. 将查询到的值赋给一个全局变量。
  4. 通过使用消息 ID 来获取先前发送的不和谐消息。
  5. 将不和谐消息编辑为步骤#3 返回的值。

我在 #5 上收到错误,因为客户端准备就绪并尝试使用未定义的值进行编辑,因为数据库查询尚未完成。

代码如下:

let newValue; //global variable

connectToDb((err) => { //connect to db
    if (!err) { //if there is no error then execute
        console.log("Database ready.");
        db = getDb();
    
        db.collection("document").findOne({id: id})
        .then((result) => {
            newValue = result.value; //assign value to global variable
        })
    }
})


client.on("ready", () => {
    console.log(`Logged in as ${client.user.tag}`);

    client.channels.cache.get(discordChannelId).messages.fetch(discordMessageId) //fetch previous msg
    .then((msg) => {
        msg.edit(newValue); //edit the previous msg with new value
    })
});

我收到此错误:无法读取未定义的属性(读取“newValue”)

javascript node.js mongodb discord.js
© www.soinside.com 2019 - 2024. All rights reserved.