javascript - firebase.firestore.FieldValue.serverTimestamp() 在我尝试插入时创建一个“修改后的”快照条目
问题描述
抱歉,我不知道这是一个问题,还是我无法以正确的方式使用它,
我面临的问题是..
我正在尝试创建一个新文档,其中包含某些字段,并创建了一个字段,当我尝试使用 onSnapshot() 侦听器检索新输入的文档时出现问题。onSnapshot() 侦听器被触发两次,添加了类型,然后触发了类型modified,因为firebase.firestore.FieldValue.serverTimestamp()的值 没有同时插入。
这是添加文档的代码片段
senderid : this.buddy.senderId,
receiverid: this.buddy.receiverId,
message : msg,
created: firebase.firestore.FieldValue.serverTimestamp()
这是阅读文档的代码:
this.db.collection(this.collectionName.friendsCollection).doc(this.buddy.docid)
.collection(this.collectionName.chatsCollection).orderBy('created')
.onSnapshot(snapshot=> {
skip.buddymessages = [];
if(snapshot.empty)
{
console.log("First Chat");
}
else{
console.log("size",snapshot.size)
snapshot.docChanges.forEach(change => {
if (change.type === 'added') {
console.log('New : ', change.doc.data());
}
if (change.type === 'modified') {
console.log('Modified : ', change.doc.data());
}
if (change.type === 'removed') {
console.log('Removed : ', change.doc.data());
}
});
这是控制台屏幕截图:-
解决方案
What you are seeing is the expected behavior. The client sees its own document information the moment it's added (your 'added' callback - this is considered an event for a local change), but since the timestamp is computed on the server, that timestamp is written later on the server, and is eventually synchronized back to the client (your 'modified' callback). The linked documentation shows how to tell if a snapshot has a pending write that hasn't been fully committed on the server.
Retrieved documents have a metadata.hasPendingWrites property that indicates whether the document has local changes that haven't been written to the backend yet. You can use this property to determine the source of events received by your snapshot listener:
db.collection("cities").doc("SF") .onSnapshot(function(doc) { var source = doc.metadata.hasPendingWrites ? "Local" : "Server"; console.log(source, " data: ", doc.data()); });
推荐阅读
- python - IndexError:索引 29 超出轴 0 的范围,大小为 29
- javascript - 为什么我不能对二维数组进行适当的迭代?
- selenium - Robotframework:找不到名称为“打开浏览器”的关键字
- ios - 返回视图控制器时大标题变为小标题
- php - PHP中的NodeJS Crypto等价物?
- php - get_results from custom_table JOINED to (INNER JOIN of user table and usermeta table)
- reactjs - ReactJS - 在组件之间传递数据
- python - 8/2(2+2) 在 python 中不起作用,但 8/2+(2+2) 和 8/2*(2+2) 可以。为什么?
- javascript - 加载脚本如何影响 window.load 事件?由于脚本可以进一步加载新脚本,window.load 会在什么时候停止?
- arrays - 随机数生成器打印图案