Javascript 检查firebase中是否存在文档

Javascript 检查firebase中是否存在文档,javascript,firebase,google-cloud-firestore,discord.js,Javascript,Firebase,Google Cloud Firestore,Discord.js,我正在编写一个discord.js bot,我想使用firestore作为数据库 client.on('message', async message => { if (message.author.bot || message.guild === null) return; let guildInfo = firestore.doc(`servers/${message.guild.id}`) if (!guildInfo.exist) { gui

我正在编写一个discord.js bot,我想使用firestore作为数据库

client.on('message', async message => {
    if (message.author.bot || message.guild === null) return;
    let guildInfo = firestore.doc(`servers/${message.guild.id}`)
    if (!guildInfo.exist) {
        guildInfo.set({
            prefix: "!",
            logsOn: false,
            logsID: 0,
            welcomeOn: false,
            welcomeID: 0,
            welcomeMessage: "",
            wordFilterOn: false
        })
    }
这是我的消息事件的开始,我希望它检查文档是否存在,是否不存在,并按照上面所示设置变量。问题在于,此代码似乎适用于每条消息,并将覆盖其自身
因此,如果我尝试更改某些内容,则下一条消息将被重置

如果您阅读上的Firestore文档,您将看到您需要调用
get()
从数据库中实际读取文档。有了这些知识,代码就会变成这样:

let guildInfo = await firestore.doc(`servers/${message.guild.id}`).get()
if (!guildInfo.exist) {
  ...

如果您的环境不支持
async
/
await
,则等效项为:

firestore.doc(`servers/${message.guild.id}`).get().then((guildInfo) => {
  if (!guildInfo.exist) {
    ...

这里有几件事需要注意:

  • get
    set
    操作是在doc上完成的,在您的情况下
    guildInfo
    (您收到
    TypeError:guildInfo.set不是一个函数
    ,因为您试图在
    get
    上执行
    set
    操作,而它应该在doc上)
  • 存在
    对您获得的对象执行
  • 代码应该是(支持
    async
    /
    wait


    如果没有
    异步
    /
    等待
    @frank van puffelen的支持,解决方案应该可以工作,除非您可能需要更改
    !guildoc.exist
    !GuidDoc.exists

    当我使用问题中显示的附加集合代码尝试上面的代码时,我得到了错误
    TypeError:guildInfo.set不是正确的函数
    ,因为
    guildInfo
    是一个
    DocumentSnapshot
    ,而
    set
    只存在于
    DocumentReference
    上。您可以执行
    guildInfo.ref.set(…)
    。在进行此类工作时,请将文档放在手边,因为我发现在那里导航类型更有效:
    let guildInfo = firestore.doc(`servers/${message.guild.id}`);
    let guildDoc = await guildInfo.get();
    
    if (!guildDoc.exists) {
       guildInfo.set( {} // your message here
       );
    }