为什么此批交易在Cloud Firestore中失败?

时间:2020-07-02 21:07:44

标签: javascript firebase react-native google-cloud-firestore

我正在为我的应用程序使用React Native,并且正在执行批处理事务,该事务在我设置的第二个批处理中失败:

let rriNshpiUserCollection = await firestore().collection('myDoc').doc(login_uid);
    let privateDoc = await firestore().collection('myDoc').doc(login_uid).collection('private');
    let batch = firestore().batch();

        batch.update(rriNshpiUserCollection, {
            addCoord: this.state.location,
            last_location: this.state.location,
            device_id: this.state.device_id,
            update_time: timeStamp,
            act: 1
        });
        batch.set(privateDoc, { // its failing here
            loc: this.state.location,
            time: timeStamp
        });

错误:

错误:firebase.firestore.batch()。set(*)'DocumentRef'是DocumentReference的预期实例。

你能告诉我代码有什么问题吗?

2 个答案:

答案 0 :(得分:2)

错误来自以下代码:

batch.set(privateDoc, {
    loc: this.state.location,
    time: timeStamp
});

原因是privateDoc是对集合的引用,您不能在集合(或集合中的set)上调用batch.set

如果您要将新文档添加到private集合中,则可以使用以下方法为此创建引用:

batch.set(privateDoc.doc(), {
    loc: this.state.location,
    time: timeStamp
});

或者(也许更好):

let privateDoc = firestore().collection('myDoc').doc(login_uid)
                            .collection('private').doc();
batch.set(privateDoc, {
    loc: this.state.location,
    time: timeStamp
});

答案 1 :(得分:1)

您的privateDoc是一个CollectionRefernce,但是错误消息告诉您需要DocumentReference。交易必须对单个文件进行操作。