gpt4 book ai didi

firebase - 创建文档时使用 mergeFields 设置的 Firestore 文档无法按预期工作

转载 作者:行者123 更新时间:2023-12-04 17:36:58 27 4
gpt4 key购买 nike

您好,我正在用这样的批处理保存文档:

batch.set(admin.firestore().collection('suuntoAppWorkoutQueue').doc(generateIDFromParts([serviceToken.userName, payload.workoutKey])), <QueueItemInterface>{
userName: serviceToken.userName,
workoutID: payload.workoutKey,
retryCount: 0,
processed: false,
}, {mergeFields: ['retryCount']});

根据文档:

Changes the behavior of set() calls to only replace the specified field paths. Any field path that is not specified is ignored and remains untouched.

上面说只会替换。

但是,当我写一个新文档时,例如文档 ID 不存在 mergeFields 只写 retryCount 字段。

这是设计使然吗?

那么不应该说:

Changes the behavior of set() calls to only write

代替:

Changes the behavior of set() calls to only replace

最佳答案

我可以理解你关于写入/替换的论点。我自己没有检查行为,但是如果文档不存在时写入字段,“写入”或“更新”将比替换更适合描述行为,因为首先没有任何内容可以替换。

如果您只想在文档已经存在的情况下更新字段,您可以使用事务来执行此操作。您可以使用事务来获取文档的最新版本,检查它是否存在,如果存在则更新它。

let data = {
userName: serviceToken.userName,
workoutID: payload.workoutKey,
retryCount: 0,
processed: false,
}

let db = admin.firestore()
let documentReference = db.collection('suuntoAppWorkoutQueue').doc(...)
db.runTransaction((transaction) =>
transaction.get(documentRef).then((doc) => {
if (doc.exists) {
return t.update(documentRef, {retryCount: data.retryCount});
} else {
return t.set(documentRef, data);
}
}
).then(...).catch(...)

事务也有原子性的好处。如果服务器上的值在您获取后发生了变化,则交易将失败。在这种情况下,Firestore 实际上会重新运行您的代码以重新尝试更新。这消除了竞争条件。

关于firebase - 创建文档时使用 mergeFields 设置的 Firestore 文档无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56355707/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com