首页 > 解决方案 > 在 Firestore 上添加数据

问题描述

我正在尝试将数据保存在 Firestore 数据库中

db.collection('clients').doc(clientInformation['id']).set(clientInformation)
        .then( result => {
            res.status(200).send({ client: result });
        });

如果提供的 id 已经存在于 db 上,我想要得到一个错误,我知道 firestore 会覆盖它或为您提供合并此数据的选项,但它可能会使用不同于“设置”并抓住它?

谢谢!

标签: javascriptgoogle-cloud-firestore

解决方案


首先尝试获取您要保存的特定信息。它不存在,写它,否则更新它。

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document already exists:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document we can .set it");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

推荐阅读