如何在Firebase中将子集合添加到新创建的文档中?

时间:2020-03-03 19:25:14

标签: javascript node.js firebase google-cloud-firestore

我正在为Firebase中的某些文档创建导入程序。

我需要为我添加的每个文档的特定属性提供一个子集合(不仅仅是数组)。

当前,我有以下代码,该代码似乎不起作用:

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);
});
  1. 我没有显示错误
  2. 我从来没有消息“评论ID ...已写”
  3. 很显然,我以书面文档结尾,但是没有任何用户评分。

我想我没有正确添加子集合。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

代码没有在终止之前等待子集合的添加完成。

此编辑将添加到子集合中的因素分解为可测试的函数,收集在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)
})