【问题标题】:Is it possible to attach a .collection().doc() to doc.ref.path?是否可以将 .collection().doc() 附加到 doc.ref.path?
【发布时间】:2020-11-12 07:17:50
【问题描述】:

我想在下面的示例中的 docPath 中创建一个新集合。是否可以在 docPath (doc.ref.path) 之后继续使用 .collection().doc()...?我不断收到此错误:无法读取未定义的属性“集合”。

出现错误的我的函数:

function comment(docPath) {

    var modalcomment = document.getElementById("modal-comment");

    modalcomment.style.display = "block";

    var submitcomment = document.getElementById("submitcomment");

    submitcomment.addEventListener('click', (e) => {

        var commentinput = document.getElementById("comment");

        db.docPath.collection('comments').doc().set({

            comment: commentinput.value,

        })
        
    })

}

我存储 docPath 变量的代码:

firebase.auth().onAuthStateChanged(function(user) {

    var query = db.collectionGroup("userPosts")

    query.get().then(querySnapshot => {
        setupPosts(querySnapshot.docs)
    })

    const posts = document.querySelector('.posts');

    const setupPosts = (data) => {
        let html = '';
        data.forEach(doc => {
            var docPath = doc.ref.path;
            console.log(docPath)
            const post = doc.data();
            const picURL = post.picURL;
            let li = `<li class="post">
                <div class="title">${post.title}</div>
                <div class="content">${post.content}</div>
                <button class="comment" onclick="comment('${docPath}')">Comment</button>
                <button class="like" onclick="like('${docPath}')">Like</button>`;
            
            li += (post.picURL ? `<img class="img" src="${post.picURL}" onclick="openImage('${picURL}')">` : ``);
            li += `</li><br></br>`;
            html += li
        })
        
        posts.innerHTML = html;
    }

docPath 显示正确的存储数据(文档的正确路径)

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    不,doc.ref.path 不可能,它是一个字符串。你不能在字符串对象上调用collection()。

    也许您想存储doc.ref 的值,它是一个DocumentReference 对象。这肯定有一个 collection() 方法,您可以使用它来构建对该文档下的子集合的更深层次的引用。

    【讨论】:

    • 那么,用 doc.ref.path 创建一个新的集合是不可能的?还有其他方法吗?
    • 我在回答中给了你选择。
    • 所以,这意味着我可以将 .collection() 直接附加到 doc.ref 上。我可以用 doc.ref 更改 doc.ref.path,它会帮助我吗?
    • 我建议你试试,是的。
    • 错误:docref.collection()..... 不是函数。 docref = doc.ref
    猜你喜欢
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多