javascript - 使用事务检查是否存在多个文档,如果不存在则添加它们

标签 javascript firebase transactions google-cloud-firestore

这是我的情况:我有一个包含很多条目的本地 json 文件。该文件未经过清理(即列表中可能有重复的条目)。我的目标是使用 firestore 将本地文件中的每个项目(一次)添加到我的数据库中。

文档说事务可以是多个 get 操作,后跟多个 update/set/delete 操作。但是,示例通常只有一个 获取。如何在不嵌套 then() 的情况下进行多个 get 操作?我想我可以得到整个集合并比较结果。但那样我就不会学会如何使用多个 get!

示例数据:

/* mock data */
var myList = [
    {
        id: '123',
        name: 'Aloha 1',
        latitude: 0.0,
        longitude: 1.1,
        url: 'https://www.google.com'
    },
    {
        id: '321',
        name: 'Aloha 2',
        latitude: 3.0,
        longitude: 3.1,
        url: 'https://www.gmail.com'
    },
    {
        id: '123',
        name: 'Aloha 1',
        latitude: 0.0,
        longitude: 1.1,
        url: 'https://www.google.com'
    },
    {
        id: '321',
        name: 'Aloha 2',
        latitude: 3.0,
        longitude: 3.1,
        url: 'https://www.gmail.com'
    }
];

这是我的尝试(我知道这是错误的,我有一系列get/set操作...):

var transaction = db.runTransaction(t => {
    for (item in myList) {
        const ref = db.collection('superList').doc(item.id);
        const sanitizedEntry = {
            name: item.name,
            location: new admin.firestore.GeoPoint(item.lat, item.lon),
            url: item.url,
        }
        t.get(ref).then(doc => {
            if (!doc.exists) {
                t.set(ref, sanitizedEntry);
            }
        });
    }
})
.then(result => {
    console.log('Transaction success!');
})
.catch(err => {
    console.log('Transaction failure:', err);
});

生成的数据库应仅包含 superList/123superList/321(以及集合中已有的任何其他文档)。

最佳答案

如果要检查的项目数固定,可以使用 getAll 来同时获取多个文档。这是一个全有或全无的结果。您要么得到所有文档,要么得到错误。

let superList = db.collection('superList');
let myRef0 = superList.doc(item[0].id);
let myRef1 = superList.doc(item[1].id);
let myRef2 = superList.doc(item[2].id);
let myRef3 = superList.doc(item[3].id);

return db.getAll(itemRef0, itemRef1, itemRef2, itemRef3).then(response => {
  // The data is returned in an array, here
}.catch(err => {
  console.error(`An error happened ${err}`);
});

关于javascript - 使用事务检查是否存在多个文档,如果不存在则添加它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48672313/

相关文章:

php - MySQL 事务是否锁定正在更新和/或选择的 InnoDB 中的行

c# - 在事务中运行 C# 代码

javascript - AngularJs:在 Controller 内格式化当前日期

javascript - Dojo 工具包 - 如何使用函数覆盖 css?

java - 如何从 Firebase 存储中检索图像的下载 URL?

Swift:Firebase 3 升级后出现 Geofire 实例化错误

javascript - 我们如何将验证应用于 WordPress 插件的任何字段

javascript - 跟踪 HTML5 视频隐藏式字幕可见性状态

node.js - 我们是否应该将 Helmet 中间件与在 Firebase Cloud Function 上运行的 Express 应用程序一起使用?

javascript - 使用 JavaScript 进行 AWS DynamoDB 事务 : One or more parameter values were invalid