我正在编写一个使用Firebase Auth / Firestore跟踪用户的健身运动的React / Redux应用程序。我有Redux Form来处理数据提交,并且我想在Firestore中实现以下示例数据结构:
users {
id {
name: 'John Smith'
uid: 'k1s7fxo9oe2ls9u' (comes from Firebase Auth)
exercises: {
{
name: 'Bench Press',
sets: 3,
reps: 10,
lbs: 100,
}
}
}
}
但是,我不知道如何继续向练习子集合中添加新的练习对象(在Firestore中,我想这将是地图的字段类型)。我想做的是在用户提交新表格时在“练习”中添加新对象。因此,例如,如果用户想添加一次硬拉练习,则如下所示:
users {
id {
name: 'John Smith'
uid: 'k1s7fxo9oe2ls9u' (comes from Firebase Auth)
exercises: {
{
name: 'Bench Press',
sets: 3,
reps: 10,
lbs: 100,
},
{
name: 'Deadlift',
sets: 3,
reps: 12,
lbs: 120,
}
}
}
}
呼叫db.collection('users').doc(doc.id).add({"exercises": values});
只是更新已经存在的Bench Press对象,而不是在提交表单时添加一个新对象。
但是调用db.collection('users').doc(doc.id).add({"exercises": values});
会给我这个错误:未捕获(承诺)TypeError:_firebase__WEBPACK_IMPORTED_MODULE_3 __。default.collection(...)。doc(...)。add不是函数。
我已经为此苦苦挣扎了很长时间了,非常感谢任何帮助。
这是我的组件:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import db from '../../../firebase';
import '@firebase/firestore';
import { store } from '../../../App';
const formSubmit = (values)=> {
const currentUserId = store.getState().auth.uid;
db.collection("users").get().then((usersSnapshot) => {
usersSnapshot.forEach((doc) => {
// looking for the current user and then updating their data
if(doc.data().uid === currentUserId) {
db.collection('users').doc(doc.id).add({
"exercises": values,
});
}
});
});
}
let ExercisesForm = ({ handleSubmit }) => (
<form onSubmit={handleSubmit(formSubmit)}>
<div>
<Field name="name" component="input" type="text" placeholder="Exercise Name" />
</div>
<div>
<Field name="sets" component="input" type="number" />
<label htmlFor="sets"> sets</label>
</div>
<div>
<Field name="reps" component="input" type="number" />
<label htmlFor="reps"> reps</label>
</div>
<div>
<Field name="lbs" component="input" type="number" />
<label htmlFor="lbs"> lbs</label>
</div>
<button type="submit">Submit</button>
</form>
)
ExercisesForm = reduxForm({
form: 'exercise'
})(ExercisesForm)
const mapStateToProps = state => ({
uid: state.auth.uid,
});
export default connect(
mapStateToProps,
undefined
)(ExercisesForm);
答案 0 :(得分:0)
您应该能够说:
db
.collection('users')
.doc(doc.id)
.collection('exercises')
.add(values);
values
包含您要添加的文档的所有字段。它将在Exercises子集合中创建一个具有随机ID的新文档。