[英]google cloud functions connect to mongodb
I am trying to connect to MongoDB in my google cloud function HTTP trigger.我正在尝试在我的 google 云函数 HTTP 触发器中连接到 MongoDB。
'use strict';
const http = require('http');
const MongoClient = require('mongodb').MongoClient;
exports.weatherWebhook = (req, res) => {
console.log(req.body);
MongoClient.connect('string', (err, client) => {
if (err) {
console.log(err)
} else {
db = client.db('chatbot')
db.collection('chatbot_params').save({ "loanType": "123", "loanAmount": "90000", "duration": "5 years", "userSession": "test-1234" }, (err, result) => {
if (err) {
console.log(err)
res.json({ "status": "err" })
} else {
res.json({ "status": "saved" })
}
})
}
})
}
but when I run the program I get an error saying that.但是当我运行程序时,我收到一条错误消息。
ReferenceError: db is not defined at MongoClient.connect
(/user_code/index.js:14:16) at result
(/user_code/node_modules/mongodb/lib/utils.js:414:17) at
executeCallback (/user_code/node_modules/mongodb/lib/utils.js:406:9)
at /user_code/node_modules/mongodb/lib/mongo_client.js:272:5 at
connectCallback
(/user_code/node_modules/mongodb/lib/mongo_client.js:946:5) at
/user_code/node_modules/mongodb/lib/mongo_client.js:816:13 at
_combinedTickCallback (internal/process/next_tick.js:73:7) at process._tickDomainCallback (internal/process/next_tick.js:128:9)
why is that?这是为什么? I have implemented the same code in my other applications(not cloud functions).
我在其他应用程序(不是云功能)中实现了相同的代码。 it seems to be working fine.
它似乎工作正常。
NOTE: I am using mongo lab to host the database
注意:我正在使用 mongo lab 来托管数据库
Please specify url for the MongoClient , as now you are just passing 'string' as url option.Have a look below请为 MongoClient 指定 url,因为现在您只是将 'string' 作为 url 选项传递。看看下面
MongoClient.connect(url, function(err, client) { // provide mongo lab url
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
Hope , this might will help you希望,这可能会帮助你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.