Javascript 检查firebase中是否存在文档
我正在编写一个discord.js bot,我想使用firestore作为数据库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
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
);
}