如何将 MongoDB 与 Cloud Functions for Firebase 结合使用?

sab*_*qui 4 mongoose mongodb firebase google-cloud-functions

我想将 Cloud Functions 用于 Firebase 和 MongoDB。问题是我不知道如何将我的 Mongo 数据库与 Cloud Functions 连接起来。我的数据库部署在 matlab 上。我做了这个架构:

var mongoose = require('mongoose')
var Schema = mongoose.Schema

var patientSchema = new Schema({

    name: {
        type: String,
        required : true,
    },

    disease:{
        type: String,
        required : true, 
    },

    medication_provided: {
        type: String,
        required : true,
    },

    date : {
        type : Date,
    }
})

const patient = mongoose.model('patientInfo', patientSchema)
module.exports = patient
Run Code Online (Sandbox Code Playgroud)

然后我需要在项目 index.js 文件中使用我的架构,并导出一个名为 getAllPatient 的函数。

const patient = require('../Patient')
const functions = require('firebase-functions');
const mongoose = require('mongoose')

mongoose.connect('mongodb://patient:patient123@ds139869.mlab.com:39869/patient',{useMongoClient: true})
exports.getAllPatient = functions.https.onRequest((request, response) => {
    patient.find({}).then((data) => {
        response.send(data)
    })
})
Run Code Online (Sandbox Code Playgroud)

但给我一个错误“错误:无法处理请求”

Ana*_*pta 5

我最近遇到了这种类型的错误,发现 firebase free 计划不允许来自函数内部的出站连接。如果您需要调用外部 http/tcp 连接,则需要在火焰或火焰计划上。请参阅下面附加的屏幕截图或在此链接处查看云功能部分 -> 出站网络Firebase 定价

在此处输入图片说明


Gau*_*rma 4

尝试以类似的方式设计云功能,如下面的链接所示:-

https://github.com/firebase/functions-samples/blob/master/authorized-https-endpoint/functions/index.js

我已经尝试过使用 mongoose 很长时间了,它工作正常,但速度很慢,因为对于每个新请求,它都会打开 mongoose 连接并为您提供数据。

希望这可以帮助!!