简体   繁体   English

将方法中的字段名称分配给Firestore文档

[英]Assigning a field name from a method to Firestore document

Let's say I have a collection called 'users'. 假设我有一个名为“用户”的集合。 When someone clicks the upvote button, I want it to update the user document with an entry that's the slug from the page they are viewing. 当有人点击upvote按钮时,我希望它用一个条目更新用户文档,该条目是他们正在查看的页面中的slug。 However, I'm not sure how to accomplish it using the code I have. 但是,我不知道如何使用我的代码完成它。

voteUp() {
        const voteup_ref = db.collection("builds").doc(this.$route.params.slug)
        const voteuser_ref = db.collection("users").doc(this.alias)
        return db.runTransaction(t => {
          return t.get(voteup_ref).then(doc => {
            const newCount = doc.data().voteup + 1
            const NewSlug = voteuser_ref
            t.update(voteup_ref, {
              voteup: newCount
            })
            t.update(voteuser_ref, {
              NewSlug: 'voteup'
            })
          });
        })
      },

So, if someone is viewing a page with the slug of 'my-awesome-comment', I want 'my-awesome-comment' to be entered in the user's document with a value of "voteup". 因此,如果有人正在查看带有'my-awesome-comment'标题的页面,我希望在用户的文档中输入“my-awesome-comment”,其值为“voteup”。

What's actually happening is that it will write an entry to the user document as I expect, but it's entering the field name as 'NewSlug' with a value of "voteup" instead of whatever the slug actually is. 实际发生的是它会像我期望的那样在用户文档中写入一个条目,但它输入的字段名称为“NewSlug”,其值为“voteup”而不是slug实际上是什么。

What am I doing wrong? 我究竟做错了什么?

The way you've written the JSON object NewSlug itself is the property name, instead of using its value. 您编写JSON对象的方式NewSlug本身是属性名称,而不是使用其值。 To do the latter, you need to use square bracket notation ( [] ): 要执行后者,您需要使用方括号表示法( [] ):

let update = {};
update[NewSlug] = 'voteup';
t.update(voteuser_ref, update)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM