node.js - 如何将元素附加到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)
所以,我不知道我应该如何使用该功能。感谢您的任何回答!
解决方案
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(...);
推荐阅读
- javascript - 如何动态生成 adwords 商业广告
- user-interface - 如何在 scilab 的 GUI 中绘制你想要的位置
- wpf - 在 DataGridTemplateColumn.CellTemplate (XAML+WPF+MVVM) 中使用 DatePicker 时的日期字符串格式
- python-3.x - Constant accepted but not defined
- python - 根据特定条件添加到字典并计算文件中的字符串
- php - Display login popup to users in wordpress on "Read more" click in posts
- c# - Unable to deserialize Json array to model object in c#
- javascript - await return undefined javascript
- powershell - File path with quotation mark issue of Powershell
- android - ListView of Linearlayouts