【发布时间】:2018-07-27 17:12:28
【问题描述】:
我已经构建了一个由 Firestore“文档创建”事件触发的 Firebase 云功能
该函数连接到 MongoDB 集群(在 MongoDB Atlas 上运行),修改 Firestore 数据将其存储在数据库的集合中
函数本身在每次写入文档时都会执行
但它没有完成执行,这是零星的,例如大约 10 次中的 1 次,执行将不会完成,即“错误连接”或“连接成功”行均未执行
同样的代码被执行了 9/10 次(大约)
这是代码的精简版
import * as functions from 'firebase-functions';
import { MongoClient } from "mongodb";
exports.migrate = functions.firestore
.document('{rootCollection}/{tenantName}/users/{userId}/entry/{entryId}')
.onCreate((snap, context) => {
const uri = "mongodb://localhost:27017/";
console.log("Attempting to connect to mongoclient");
MongoClient.connect(uri, function(err, client) {
if (err) {
console.log("error connecting");
return 1;
}
else if (client) {
console.log("Connected to mongoclient");
//write to mongodb collection here
}
});
});
这是一次成功的执行,红色的日志消息突出显示了在 MongoClient 连接后执行的块内的代码(打印了一些额外的日志消息)
这是一个不成功的执行
编辑:
Doug 的回答提示,这就是我解决它的方法 - 我们不仅需要返回一个承诺,还需要链接连接返回的承诺和插入语句
exports.migrate = functions.firestore
.document('{rootCollection}/{tenantName}/users/{userId}/entry/{entryId}')
.onCreate((snap, context) => {
const uri = "mongodb://localhost:27017/";
console.log("Attempting to connect to mongoclient");
return MongoClient.connect(uri).then((client) => {
console.log("Connected successfully");
return client.db("test")
.collection("testcollection")
.insertOne({"name": "1"})
.then((() => {
console.log("inserted successfully");
client.close(true)
.then(()=>{console.log("connection close OK")})
.catch(()=>{console.log("connection close Err")});
}))
.catch(() => {
console.log("error in insertion");
client.close(true)
.then(()=>{console.log("connection close OK")})
.catch(()=>{console.log("connection close Err")});
});
})
.catch(() => console.log("connection failure"));
而且我确定这一次,因为我可以在云功能日志中看到它们,所以代码按照我想要的顺序执行:
- 功能已启动(系统消息)
- 正在尝试连接(用户消息)
- 连接成功(用户消息)
- 插入成功(用户消息)
- 连接已关闭(用户消息)
- 功能结束(系统消息)
【问题讨论】:
标签: mongodb firebase google-cloud-functions