我是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
我在这个错误上停留了一个星期,现在我很失落。
答案 0 :(得分:0)
您需要研究的两件事:-
1)在通过nodeJs创建数据库时,检查mongodb是否已正确安装并在计算机上运行,并记住除非创建记录,否则您将无法在mongo中实际创建数据库数据库已创建!
如果需要,请检查此链接以了解如何安装mongo:https://docs.mongodb.com/v3.0/tutorial/install-mongodb-on-os-x/
2)检查在使用require()进行导入时,是否已在工作的应用程序目录上(本地)安装了mongodb模块。
如果是,那么您的以下代码应该可以正常工作-无需将localhost更改为您的IP,除非您遇到任何连接问题:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/MyDB"; // mydatabase is the name of db
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});