Reputation: 133
I want to use Cloud Functions for Firebase and MongoDB. The problem is I don't know how to connect my Mongo database with Cloud Functions. My database is deployed at matlab. I made this schema:
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
Then I require my schema in project index.js file, and export a function called getAllPatient.
const patient = require('../Patient')
const functions = require('firebase-functions');
const mongoose = require('mongoose')
mongoose.connect('mongodb://patient:[email protected]:39869/patient',{useMongoClient: true})
exports.getAllPatient = functions.https.onRequest((request, response) => {
patient.find({}).then((data) => {
response.send(data)
})
})
but gives me an error that "Error: could not handle the request"
Upvotes: 5
Views: 6869
Reputation: 1874
Alternative:
JUN 2023
TLDR; - Use Data API instead of connection. link
here is How to enable data API & Get MONGO_DATAAPI_URL
& MONGO_DATAAPI_KEY
.
exports.getAllPatient = functions.https.onRequest((request, response) => {
const data = {
dataSource: dataSource,
database: dbName,
collection: collectionName,
};
const config = {
method: "post",
url: MONGO_DATAAPI_URL + "/action/find",
headers: {
"Content-Type": "application/json",
"Access-Control-Request-Headers": "*",
"api-key": MONGO_DATAAPI_KEY,
Accept: "application/ejson",
},
data: JSON.stringify(data),
};
axios(config)
.then(function (resp) {
response.send(resp.data);
})
.catch(function (error) {
response.status(400).send(JSON.stringify(error));
});
});
Explanation :
MongoDB allows a service called Data API to connect to MongoDB Atlas from any platform that supports HTTPS including
- Web browsers
- Web servers
- CI/CD pipelines
- Serverless & Edge compute environments
- Mobile applications
- Internet-Of-Things devices
For More : https://www.mongodb.com/docs/atlas/api/data-api-resources/ https://www.mongodb.com/docs/atlas/api/
Upvotes: 1
Reputation: 738
I was recently facing this type of error and found that firebase free plan doesn't allow the outbound connections from within the functions. If you need to call external http/tcp connections, you are required to be on the flame or blaze plan. see the screenshot attached below or see the section cloud functions -> outbound networking at this link Firebase Pricing
Upvotes: 5
Reputation: 421
Try to design the cloud function in a similar way shown in a link below:-
I've tried with mongoose long time back and it was working fine and but it's slow because for every new request it's going to open the mongoose connection and serve you the data.
Hope this helps!!
Upvotes: 4