首页 > 解决方案 > 如何将元素附加到firestore文档中的数组中?

问题描述

我是firestore函数和数据库的新手,所以我有点卡住了。我有这个文件:

数据库文件

如您所见,现在答案在一个空数组中,但我会有一堆字符串。

问题是我使用的云功能失败了。这是我的功能

exports.registerUserResponse = functions.https.onRequest((request, response) => {

    const original = request.body;
    const type_form_id = original.form_response.form_id

    var userRef = admin.firestore().collection('users').doc(user_email);

    var transaction = admin.firestore().runTransaction(t => {
        return t.get(userRef)
          .then(doc => {
            console.log(doc.data());
            var newAnswer = doc.data().answers.arrayUnion(type_form_id);
            t.update(userRef, {answers: newAnswer});
          });
    }).then(result => {
        //return response.status(200).send();
        return response.status(200).json({result: `Message added.`}).send();
    }).catch(err => {
        console.log(err);
        return response.status(500).json({result: `Message: ${err} error.`}).end();
    });

所有的值都很好,但是我在 arrayUnion 函数中遇到了这个错误

TypeError: Cannot read property 'arrayUnion' of undefined
at t.get.then.doc (/user_code/index.js:27:58)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

所以,我不知道我应该如何使用该功能。感谢您的任何回答!

标签: node.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


arrayUnion 不是您可以从 Firestore 查询中获取的任何数据项上存在的方法。您进入的 undefined 的值绝对不可用doc.data().answers

看起来您可能对如何使用FieldValue.arrayUnion()感到困惑。您不需要交易即可使用它。只需按照文档中的说明执行更新:

var washingtonRef = db.collection('cities').doc('DC');

// Atomically add a new region to the "regions" array field.
var arrUnion = washingtonRef.update({
  regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
});

你的可能看起来像这样:

admin.firestore().collection('users').doc(user_email).update({
    answers: admin.firestore.FieldValue.arrayUnion(type_form_id)
}).then(...);

推荐阅读