2

我是 nodeJS 和 mongodb 的新手。我从 YouTube 学到了所有这些东西。我尝试使用 node.js 创建一个 api,但现在我什至无法连接到 mongodb。

问题是我使用 Fn 项目(运行时节点)并尝试连接到 mongodb 但它不起作用。(Fn 项目是一个开源容器原生无服务器平台。)

这是我用来连接 mongodb 的部分:

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/MyDB';

MongoClient.connect(url,function(err, db) {
   if(err) throw err;
   console.log("Database is Connected!");
   db.close();
});

//This is the part that Fn Project generated automatically
var fdk = require('@fnproject/fdk');

fdk.handle(function(input){
var name = 'World';
    if (input.name) {
        name = input.name;
    }
response = {'message': 'Hello ' + name}
return response;
})

所以我运行命令来启动 Fn 服务器

fn start

我还运行命令来启动 mongodb

sudo mongod

一切设置好后,我在部署前运行命令来执行代码。

sudo fn run

这是我得到的结果:

Building image nodefn:0.0.3 ...
(node:1) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
/function/node_modules/mongodb/lib/operations/mongo_client_ops.js:466
      throw err;
      ^

Error: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
    at Pool.<anonymous> (/function/node_modules/mongodb-core/lib/topologies/server.js:564:11)
    at emitOne (events.js:115:13)
    at Pool.emit (events.js:210:7)
    at Connection.<anonymous> (/function/node_modules/mongodb-core/lib/connection/pool.js:317:12)
    at Object.onceWrapper (events.js:318:30)
    at emitTwo (events.js:125:13)
    at Connection.emit (events.js:213:7)
    at Socket.<anonymous> (/function/node_modules/mongodb-core/lib/connection/connection.js:246:50)
    at Object.onceWrapper (events.js:316:30)
    at emitOne (events.js:115:13)

我的 docker 版本是 Docker 版本 18.06.1-ce,Ubuntu 版本是 Ubuntu 18.04.1 LTS。

另外,这是 package.json 和 func.yaml

{
    "name": "hellofn",
    "version": "1.0.0",
    "description": "backend",
    "main": "func.js",
    "author": "",
    "license": "Apache-2.0",
    "dependencies": {
        "@fnproject/fdk": "0.x",
        "mongodb": "^3.1.4"
    }
}

--

//func.yaml
schema_version: 20180708
name: nodefn
version: 0.0.3
runtime: node
entrypoint: node func.js
format: json
triggers:
    - name: nodefn-trigger
      type: http
      source: /nodefn-trigger

我被这个错误困了一个星期,现在我很迷茫。

4

0 回答 0