[英]How to add a sub collection to a freshly created document in firebase?
I'm creating an importer for some documents in firebase.我正在为 firebase 中的一些文档创建一个导入器。
I need to have a sub collection(not just an array) for a specific property of each document I add.我需要为我添加的每个文档的特定属性创建一个子集合(不仅仅是一个数组)。
Currently I've the following code, which doesn't seems to work:目前我有以下代码,它似乎不起作用:
let rawdata = fs.readFileSync("files/" + file);
let spot = JSON.parse(rawdata);
var spotFirebase = {
id: spot.Id,
sourceId: spot.SourceId,
type: spot.Type,
location: new firebase.firestore.GeoPoint(spot.Latitude, spot.Longitude),
description: spot.Description,
address: spot.Address,
city: spot.City,
country: spot.Country,
price: spot.Price,
parkingCost: spot.ParkingCost,
opening: spot.Opening,
name: spot.Name,
features: spot.Features,
activities: spot.Activities,
rating: {
ratingCount: spot.Rating.RatingCount,
ratingAverage: spot.Rating.RatingAverage
}
}
db.collection("spots").add(spotFirebase).then(function (docRef) {
console.log("Document ", file, " written with ID: ", docRef.id, ", index: ", index, ". ", spot.Rating.UserRatings.length);
spot.Rating.UserRatings.forEach(ur =>
docRef.collection("userRatings").add(
{
date: ur.Date,
username: ur.UserName,
review: ur.Review,
note: ur.Note,
reviewSource: ur.ReviewSource
}).then(function (subDocRef) {
console.log("Review ID ", subDocRef.id, " written");
}).catch(function (errorReview) {
console.error("Error adding document: ", errorReview);
}));
})
.catch(function (error) {
console.error("Error adding document: ", error);
});
I guess I'm not adding correctly the sub collection properly.我想我没有正确添加子集合。
What did I do wrong?我做错了什么?
The code wasn't waiting for the additions to the sub collection to complete before terminating.在终止之前,代码不会等待子集合的添加完成。
This edit factors the addition into the subcollection into a testable function, collects the promises to create each new doc in a promises
array, then waits for all of those ( Promise.all()
) to complete before terminating...此编辑将添加到子集合中的内容分解为可测试的函数,收集承诺以在promises
数组中创建每个新文档,然后在终止之前等待所有这些( Promise.all()
)完成...
function addUserRating(parentRef, ur) {
const newDoc = {
date: ur.Date,
username: ur.UserName,
review: ur.Review,
note: ur.Note,
reviewSource: ur.ReviewSource
}
return parentRef.collection("userRatings").add(newDoc).then(result => {
console.log("Review ID ", result.path, " written");
return result
})
}
db.collection("spots").add(spotFirebase).then(function (docRef) {
console.log("Document ", file, " written with ID: ", docRef.id, ", index: ", index, ". ", spot.Rating.UserRatings.length);
let promises = spot.Rating.UserRatings.map(ur => addUserRating(docRef, ur))
return Promise.all(promises)
}).catch(function (error) {
console.error("Error adding document(s): ", error)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.