【问题标题】:How can I, when adding a document to firestore, write it to another document with a different name? [closed]在将文档添加到 Firestore 时,如何将其写入另一个具有不同名称的文档? [关闭]
【发布时间】:2019-11-26 08:56:32
【问题描述】:

将文档添加到 Firestore 时,我尝试将其转移到另一个名称并删除旧文档。我不明白该怎么做。似乎有可能以某种方式设置触发器来执行 firebase 函数中的特定函数?

为了更改文档的名称,我尝试从另一个文档中提取文档的数量,但似乎我弄错了。

exports.changeLocation = functions.region('europe-west1').firestore.document('users/{userId}/notes/{noteId}').onCreate((snap,context) => {
  const uid = context.params.userId;
  const data = snap.data();
    let count;
    let documentRef = db.collection("users").doc(uid).collection("info").doc("info").get().then(doc => {
    if(!doc.exists){
      console.log("No such document");
    }else{
      count = doc.id("countMutable").toString();
    }
  }).catch(err => {
    console.log("Error getting document: ", err);
  });
  const p2 = documentRef.delete();
  return db.collection("users").doc(uid).collection("notes").doc("its_notes:"+count).set(data);
});

【问题讨论】:

  • 有点难以理解你到底想要做什么......你真的有一些像"its_notes:" + count这样的文档吗?您能否制作图表或在项目符号列表中解释您的用例的确切流程。哪个doc保存数据,哪个要更新,哪个要删除。另请注意,您需要链接异步方法返回的 Promises。我建议您观看 Firebase 视频系列中有关“JavaScript Promises”的 3 个视频:firebase.google.com/docs/functions/video-series

标签: firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

你的问题不够清楚。但根据您解释的第一行,我假设当创建一个新文档时,您希望将其数据转换为不同路径/子集合上的另一个文档,然后删除第一个文档。

假设您有一个函数,每当在此路径创建文档时就会触发该函数:users/{userId}/notes/{noteId} 然后你想在这个路径添加另一个包含这个新创建的数据的文档:users/{userId}/info(文档 id 正在由 firestore 生成,除非您想以不同的方式管理它),然后删除第一个文档。

你可以这样做:

export const changeLocation = functionBuilder.firestore.document('users/{userId}/notes/{noteId}')
  .onCreate(async (snapShot,context) => {
  const uid = context.params.userId;
  const noteId = context.params.noteId;
  const data = snapShot.data();

  const newCollectionRef = db.collection('users').doc(uid).collection('info');
  await newCollectionRef.add(data);

  const alreadyExistedDocument = db.collection('users').doc(uid).collection('notes').doc(noteId);
  await alreadyExistedDocument.delete();
}); 

【讨论】:

    【解决方案2】:

    如果countMutable 确实是info 记录的一个字段,您不应该使用count = doc.get("countMutable").toString() 而不是count = doc.id("countMutable").toString() 吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 2018-07-30
      • 2011-03-03
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      相关资源
      最近更新 更多