Node.js 通过云函数写入云firestore不工作
我试图将数据从云函数写入云firestore,但我无法让它正常工作。以下是我在云函数中的代码:Node.js 通过云函数写入云firestore不工作,node.js,firebase,express,google-cloud-firestore,google-cloud-functions,Node.js,Firebase,Express,Google Cloud Firestore,Google Cloud Functions,我试图将数据从云函数写入云firestore,但我无法让它正常工作。以下是我在云函数中的代码: const functions = require('firebase-functions'); const admin = require('firebase-admin'); var express = require('express'); admin.initializeApp(functions.config().firebase); const app = express(); let
const functions = require('firebase-functions');
const admin = require('firebase-admin');
var express = require('express');
admin.initializeApp(functions.config().firebase);
const app = express();
let db = admin.firestore();
app.get('/helloworld', (req, res) => res.send('Hello World!'));
app.post('/signup', (req, res) => {
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
//creating document. Here is where it isn't working
let docRef = db.collection('UsersMain').doc('firstdoc');
let data = {
Email: 'a@gmail.com',
UserName: 'Matt'
};
let setDoc = docRef.set(data);
console.log(db);
res.send('Login Complete');
});
const api1 = functions.https.onRequest(app);
module.exports = {api1};
以下是我的firestore权限:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
有人能看一下,让我知道我做错了什么吗?理想情况下,将创建一个名为“firstdoc”的新文档,其中包含电子邮件和用户名数据。谢谢 查看代码时首先想到的是,在将结果发送回调用方之前,您不会等待
docRef.set(data)
完成。这意味着云功能可能会在对Firestore的写入完成之前杀死您的环境
为了确保写入操作完成,您应该只在完成对数据库的写入后才将结果写入响应。比如:
docRef.set(data).then(() => {
res.send('Login Complete');
})
谢谢@Frank van Puffelen!我现在收到一个权限被拒绝的错误。我现在正在研究这个问题,当我找到答案时,我几乎肯定会选择你的答案。我仍然收到“错误:7权限\u拒绝:缺少或权限不足”。firestore权限与上面列出的相同。你有什么想法吗?在你的问题中,你没有说任何关于被拒绝许可的事情,是吗?无论如何:云函数使用AdminSDK访问Firestore,这意味着它们绕过了数据库的安全规则。如果这个错误确实来自你的云功能,那不是因为安全规则。嗨@Frank van Puffelen。对不起,再次谢谢你!我会接受你的回答并提出一个新问题。我对此完全不知所措。