如果不存在,FireStore会创建一个文档

TSR*_*TSR 16 node.js firebase google-cloud-firestore

我想更新这样的文档:

db.collection('users').doc(user_id).update({foo:'bar'})
Run Code Online (Sandbox Code Playgroud)

但是,如果doc user_id不存在,则上面的代码将引发错误.因此,如果不存在,如何告诉Firestore创建学生,换句话说,行为如下:

db.collection('users').doc(user_id).set({foo:'bar'})
Run Code Online (Sandbox Code Playgroud)

J. *_*Doe 29

我想你想用这个代码:

db.collection('users').doc(user_id).set({foo:'bar'}, {merge: true})
Run Code Online (Sandbox Code Playgroud)

这将使用提供的数据设置文档,并保持其他字段不变.

  • 就我而言,我需要使用 update("field_name", admin.firestore.Fieldvalue.increment(1)) 来增加计数器。合并选项不适用于这种情况。我该如何实现这一目标? (7认同)
  • 请注意,它与使用更新不同 - 如果您删除模型中的字段(使用js“delete”关键字)并使用“set+merge”,则该字段将保留在数据库中,而使用更新将删除其中的字段数据库如预期。可能的方法可能是不使用js删除,而是将字段设置为null。 (3认同)

Dal*_*Zak 8

如果你需要的东西喜欢createdupdated时间戳,您可以使用此技术:

let id = "abc123";
let email = "john.doe@gmail.com";
let name = "John Doe";
let document = await firebase.firestore().collection("users").doc(id).get();
if (document && document.exists) {
  await document.ref.update({
    updated: new Date().toISOString()
  });
}
else {
  await document.ref.set({
    id: id,
    name: name,
    email: email,
    created: new Date().toISOString(),
    updated: new Date().toISOString()
  }, { merge: true });
}
Run Code Online (Sandbox Code Playgroud)

如果它不存在createdupdated时间戳,这将创建文档,但updated如果存在,则仅更改时间戳。

  • 并且切勿使用 firestore 用户客户端时间戳,始终使用“FieldValue.serverTimestamp()” (3认同)
  • 您可能还想查看 Firestore 事务:https://firebase.google.com/docs/firestore/manage-data/transactions#transactions (2认同)
  • 我不同意时间戳。Firebase 时间戳是具有添加方法的对象。如果将数据传输到其他系统(例如关系数据库),您将丢失这些方法,可能会破坏数据。出于这个原因,我们始终使用 UTC 时间戳。 (2认同)