【问题标题】:How to check if there is a defined value in the database - Discord.js如何检查数据库中是否存在已定义的值 - Discord.js
【发布时间】:2021-06-03 07:11:43
【问题描述】:

如何检查我是否在数据库中定义了一个值?如果没有设置值,我希望机器人设置一个值。

我正在使用db.value() === null 并设置所有值,但我认为有更好的方法可以做到这一点,因为当机器人在数据库中设置值时,用户必须再次运行命令,并且我的想法是:如果值不存在,则在数据库中定义,命令正常执行。

我的代码:

database.ref(`Servidores/${message.guild.id}/Users/${message.author.id}/Economia`).once('value').then(async function(db){

    let dbref = database.ref(`Servidores/${message.guild.id}/Users/${message.author.id}/Economia`);

    if (db.val() === null) {
        dbref.update({
            id: message.author.id,
            money: 0,
            daily: 0
        })

        return message.channel.send(`${message.author} Acabamos de te registrar no banco de dados. Utilize o comando novamente.`)

    }

    if (db.val().daily !== null ) {
        //command
    }
})

【问题讨论】:

    标签: node.js firebase firebase-realtime-database discord.js


    【解决方案1】:

    正如 Tarik Huber 所说,您可以使用DataSnapshot.exists() 方法来检查数据是否存在。

    至于防止用户再次运行命令,你可以巧妙地使用async/await,如下所示:

    // create a reference to the database location
    const dbref = 
    database.ref(`Servidores/${message.guild.id}/Users/${message.author.id}/Economia`);
    
    // retrieve data from the reference
    let db = await dbref.once('value');
    
    // if the data doesn't exist
    if (!db.exists()) {
      // update your data
      await dbref.update({
        id: message.author.id,
        money: 0,
        daily: 0
      });
    
      // update your `db` value to the new db value
      db = await dbref.once('value');
    }
    
    // this will either be the updated data (if there was no data before) 
    // or the old data
    if (db.val().daily !== null) {
      //command
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用exists() 检查您获得的快照。你可以这样称呼它:

      
       if (snapshot.exists()){
            const data = snapshot.val();
            console.log("exists", data);
          }
      

      您的代码如下所示:

      database
        .ref(`Servidores/${message.guild.id}/Users/${message.author.id}/Economia`)
        .once("value")
        .then(async function (db) {
          let dbref = database.ref(
            `Servidores/${message.guild.id}/Users/${message.author.id}/Economia`
          );
      
          if (!db.exists()) {
            dbref.update({
              id: message.author.id,
              money: 0,
              daily: 0,
            });
      
            return message.channel.send(
              `${message.author} Acabamos de te registrar no banco de dados. Utilize o comando novamente.`
            );
          }
      
          if (db.exists() && db.val().daily !== null) {
            //command
          }
        });
      
      

      【讨论】:

        猜你喜欢
        • 2021-08-19
        • 1970-01-01
        • 2020-07-15
        • 2011-12-10
        • 2011-05-16
        • 2021-10-10
        • 1970-01-01
        • 1970-01-01
        • 2011-12-22
        相关资源
        最近更新 更多