![](/img/trans.png)
[英]How to add Document with Custom ID to firestore in firestore 9
[英]How can I add to Firestore without specifying a document ID and utilising Firestores auto ID generator?
我正在 Dialogflow 上构建一个聊天机器人,并使用 Firestore 作为我的数据库。 我最初使用的是自定义自动 ID 生成器,但我现在尝试在内置的 Firestore 中使用,并且当前代码出现错误。
function AddWaterConsumption (agent) {
// Get parameter from Dialogflow with the string to add to the database
var databaseEntry = {
"PatientID": agent.parameters.Patient_ID,
"DailyConsumption": agent.parameters.Water_consumption_user,
"DailyWaterPlan": agent.parameters.Daily_water_plan,
};
let Patient_ID = agent.parameters.Patient_ID;
console.log(`Okay, we're trying to write to database: ${databaseEntry}`);
// here is where changes are needed
const dialogflowAgentRef = db.collection("WaterConsumption").doc(genRand(8)); // need to change to add()
console.log(`Found agent ref: ${dialogflowAgentRef}`);
return db.runTransaction(t => {
t.set(dialogflowAgentRef, databaseEntry); // this will also need to be changed
return Promise.resolve('Write complete');
}).then(doc => {
agent.add(`I have updated your daily water consumption`);
agent.add(`Is anything else I can do for you?.`);
}).catch(err => {
console.log(`Error writing to Firestore: ${err}`);
agent.add(`Failed to write "${dialogflowAgentRef}" to the Firestore database.`);
});
}
我已将重要的行更改为:
console.log(`Okay, we're trying to write to database: ${databaseEntry}`);
const dialogflowAgentRef = db.collection("WaterConsumption"); // changed here
console.log(`Found agent ref: ${dialogflowAgentRef}`);
return db.runTransaction(t => {
t.set(db.collection("WaterConsumption").add(databaseEntry), databaseEntry); // and here
它确实成功写入数据库并自动生成一个 ID。 虽然正在捕获错误:
参数“documentRef”不是有效的 DocumentReference。 输入不是普通的 JavaScript object
这没有任何意义:
t.set(db.collection("WaterConsumption").add(databaseEntry), databaseEntry);
在这一行中, db.collection("WaterConsumption").add(databaseEntry)
是对 Firestore 的调用,以在事务之外创建文档)。 相反,您想要创建一个具有唯一 ID 的新DocumentReference
,这可以使用doc()
完成(如添加文档文档中的第三个片段所示)。
所以:
const newDocRef = db.collection("WaterConsumption").doc();
t.set(newDocRef, databaseEntry);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.