【问题标题】:Unable to connect to MongoDB from NodeJS, deployed as action in OpenWhisk无法从 NodeJS 连接到 MongoDB,部署为 OpenWhisk 中的操作
【发布时间】:2018-08-28 18:36:36
【问题描述】:

我用下面的代码写了一个名为 app.js 的文件。 MongoDB 安装在 192.168.16.1 上,这是我的笔记本电脑。当我使用 node app.js 命令运行它时,我收到一条消息“已连接”。

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


    var mongoose = require('mongoose');
    var MongoClient = require('mongodb').MongoClient;
// Connect to the db
    MongoClient.connect("mongodb://192.168.16.1:27017/angularcrud", function (err, db) {

     if(err) {console.log(err); }
     else {console.log('connected');}

});

\

我在笔记本电脑上使用 Vagrant 设置了 OpenWhisk 环境。如果是 ssh 到 vagrant 并 ping 到 192.168.16.1,我会收到 ping 响应,所以我确信 vagrant VM 能够到达 192.168.16.1。我在 NodeJS 中编写了以下代码来创建 OpenWhisk 操作。我已将它作为 .zip 文件部署到 openwhisk 中(其中还包括 Node_modules 文件夹)。

function entryPoint(args) {


    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var message = "Connection not SET";

    var mongoose = require('mongoose');
    var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://193.168.16.1:27017/angularcrud", function (err, db) {

     if(err) {return err;}
      else {return 'success';}



});
}

module.exports.main = entryPoint;

如果我在 OpenWhisk 中运行上述代码,我会得到一个结果 {}。如果我删除 MongoClient.Connect 语句并返回一个简单的字符串,那么当我调用该操作时就会得到该字符串。我确信在 OpenWhisk 上运行时 MongoClient.Connect 有问题。但是,我真的被困住了,因为我没有错误地告诉我出了什么问题。

【问题讨论】:

    标签: node.js openwhisk


    【解决方案1】:

    entryPoint 函数执行一个异步函数来连接数据库。执行异步函数调用时,您需要从操作处理程序返回一个 Promise。这可确保平台在完成调用之前阻塞该异步结果。

    function main() {
      return new Promise((resolve, reject) => {
        MongoClient.connect(URL,  (err, db) => {
          if(err) return reject(err)
          resolve({message: "success"})
        })        
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 2018-01-21
      • 2023-02-07
      • 2021-05-24
      相关资源
      最近更新 更多