【问题标题】:DiscordJS/MongoDB How to get bot to update value correctlyDiscordJS/MongoDB 如何让机器人正确更新值
【发布时间】:2020-12-09 05:50:24
【问题描述】:

所以我正在尝试创建一个函数,当执行命令时,机器人会在 mongoDB 中查看 Clue1_Status 是真还是假。当它为真时,机器人结束进程,但如果为假,机器人将状态更新为真。我没有收到任何错误,但 'false' 没有更新为 true。

代码如下:

const collection = db.collection('clues')

            if(collection.find({
                "Clue1_Status" : "True" })) {
                    return;
                }

            else if(collection.find({
                "Clue1_Status" : "False" })) {
                    await configDB1.updateOne({
                        Clue1_Status: "True"
                    })
                }

【问题讨论】:

    标签: node.js mongodb discord.js


    【解决方案1】:

    啊哈,多亏了另一个答案,我更改了一些代码,所以现在它似乎可以工作了:

    const collection = db.collection('clues')
    
                if (
                    collection.find({ Clue1_Status: "True" }, (err, data) => {
                    if (err) console.error(err)
                      return data;
                    })
                  )
                    return;
                  
                  collection.find({ Clue1_Status: "False" }, async (err, data) => {
                    if (err) console.error(err)
                    if (data) {
                        await configDB1.updateOne({
                        
                        Clue1_Status : "True"
                        
                        })
                    }
                })
    

    【讨论】:

      【解决方案2】:

      db.collection.find() 仍然会返回 true,即使它没有找到任何东西。正确的写法是:

      if (
        collection.find({ Clue1_Status: "True" }, (err, data) => {
          return !!data;
        })
      )
        return;
      
      collection.find({ Clue1_Status: "False" }, (err, data) => {
        if (data) {
          data.Clue1_Status = "True";
          data.save();
      });
      

      【讨论】:

      • 谢谢,但有一个问题,那不是更新“假”吗?
      • 啊,我包括:if (err) console.error(err) 并发现错误是:TypeError: data.save is not a function 我将尝试包括:data = configDB1.update(),因为我正在尝试更新现有值?我认为
      猜你喜欢
      • 2021-08-06
      • 2020-08-30
      • 2022-01-11
      • 2020-06-06
      • 2020-02-15
      • 2018-09-18
      • 1970-01-01
      • 2018-12-17
      • 2021-10-30
      相关资源
      最近更新 更多