使用firebase函数向firestore数据库添加数据



从外部api获取的数据未保存在firestore数据库

但是我添加的姓xxxxx的记录是成功的等待db.collection(硬币)。add({lastName: 'xxxxxxx'})这可以工作,但下面的代码不

exports.firestoreKaydet = functions.firestore
.document("/users/{userId}")
.onCreate(async (snap, context) => {
await db.collection("coins").add({ lastName: "xxxxxxx" });
fetch(
"https://api.coinecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=true"
)
.then((response) => response.json())
.then(async (data) => {
data.forEach(async (coin) => {
await db.collection("coins").add({
name: coin.name,
});
});
})
.catch((error) => {
console.error(error);
});
});
const { request } = require('express');
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp();
const db = admin.firestore();

exports.firestoreKaydet=functions.firestore.document('/users/{userId}')
.onCreate(async (snap, context) => {

const response = await 
fetch('https://api.coingecko.com/api/v3/coins/markets? 
vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=true');
const data = response.json();;
const promises = [];
await data.forEach(async coin => {
promises.push(db.collection('coins').add({
name: coin.name
}));
});
return Promise.all(promises)
});

你不应该在forEach()循环中使用async/await,参见"JavaScript: async/await with forEach()"one_answers"使用async/await和forEach循环"

Promise.all()的用法如下:

exports.firestoreKaydet = functions.firestore.document('/users/{userId}').onCreate(async (snap, context) => {

try {

// db shall be defined as admin.firestore()
await db.collection('coins').add({ lastName: 'xxxxxxx' });
const response = await fetch("https://api.coinecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=true");
const data = response.json();
const promises = [];
data.forEach(coin => {
promises.push(db.collection('coins').add({
name: coin.name
}));
});
return Promise.all(promises);

} catch (error) {
console.error(error);
return null;
}

});

更新:在帮助您调试之后,似乎没有安装fetch。在functions目录下安装它,如下所示

npm install node-fetch

然后在index.js文件中放入下面的行:

import fetch from "node-fetch";

相关内容

  • 没有找到相关文章

最新更新