这是我的情况:我有一个包含很多条目的本地 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/123
和 superList/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/