【问题标题】:Pass variable into collection(collectionName).doc(docName)将变量传递给 collection(collectionName).doc(docName)
【发布时间】:2021-07-30 02:26:03
【问题描述】:

我正在创建一个云存储功能。我现在需要的最后一步是使用 userId 来检索文档。

在这里我得到了 userId 常量 userId = snap.data().userId;

这里我想插入来自 userId 的值来检索正确的文档。

const deviceDoc = db.collection('device').doc(**userId**); <<< THIS IS THE PROBLEM

const deviceData = await deviceDoc.get();
const deviceToken = deviceData.data().token;

我不知道如何使用变量 userId 将值插入到 .doc(userId) 中以获取数据。

如果 userId = 12345 我希望该行如下所示:

const deviceDoc = db.collection('device').doc('12345');

我尝试过 .doc('userId')、.doc('${userId}') 以及其他东西。这些都不起作用。

我该怎么做?

【问题讨论】:

  • db.collection('device').doc(userId) 应该可以工作。当你使用它时会发生什么?
  • 我认为它正在工作。但是,现在我需要从“deviceDoc”中提取数据。到目前为止,我已经尝试了这两行代码,但都不起作用: const deviceData = await deviceDoc.token.get; const deviceId = await deviceDoc.data().deviceToken;
  • 这是日志中的错误:onTrxnCreate TypeError: Cannot read property 'get' of undefined

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


【解决方案1】:

根据 Puf 的响应,您可以简单地使用 doc(userId)。您的其余代码看起来不错,因此您获得的文档可能不存在。请尝试以下操作:

const deviceRef = db.collection('device').doc(userId);
// you can shorten this to >> const deviceRef = db.doc(`device/${userId}`);

try {
  const deviceDoc = await deviceRef.get();
  if (!deviceDoc.exists) {
    console.log(`The document for user ${userID} does not exist`);
  } else {
    const {token} = deviceDoc.data();
    console.log('The token is:', token);
  }
}
catch (err) {
  console.error(err);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2020-01-24
    • 2012-02-13
    • 2014-09-05
    • 2011-10-13
    • 2013-12-07
    • 2014-04-30
    • 2014-12-02
    相关资源
    最近更新 更多