我一直在学习Udemy课程,以学习mongodb,并且由于导师使用基于云的思想(cloud9),所以我也决定使用相同的语言。但是,由于cloud9现在需要AWS帐户,因此我想到了使用CodeSandbox。但是我不知道如何在上面启动Mongo服务器。在安装Mongod和MongoDB之后,如果我尝试运行app.js,它会给我错误:
(node:1297) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on firstconnect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/sandbox/node_modules/mongodb/lib/core/topologies/server.js:433:11)
at Pool.emit (events.js:198:13)
at createConnection (/sandbox/node_modules/mongodb/lib/core/connection/pool.js:577:14)
at connect (/sandbox/node_modules/mongodb/lib/core/connection/pool.js:1007:11)
at makeConnection (/sandbox/node_modules/mongodb/lib/core/connection/connect.js:31:7)
at callback (/sandbox/node_modules/mongodb/lib/core/connection/connect.js:247:5)
at Socket.err (/sandbox/node_modules/mongodb/lib/core/connection/connect.js:276:7)
at Object.onceWrapper (events.js:286:20)
at Socket.emit (events.js:198:13)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
(node:1297) UnhandledPromiseRejectionWarning: Unhandled promise rejection. Thiserror originated either by throwing inside of an async function without a catchblock, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1297) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
如果我尝试运行mongod,它说
mongod: command not found
这是我的app.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/yelp_camp");
我已经尝试使用codeandbox的UI安装mongo和mongod,使用终端(npm install),并执行cloud9的文档所说的(我知道它不起作用,但是我找不到任何Codesandbox文档)
是否可以在codeandbox中执行此操作,或者我必须使用MongoAtlas?预先感谢!
我认为CodeSandbox上没有数据库托管,因此您应该使用外部服务。
您可以使用的某些服务:
一个简单的示例函数将是:
let initMongo = async () => {
try {
await mongoose.connect(
"mongodb://<dbUsername>:<dbPassword>@ds123456.mlab.com:49878/testdatabase",
{
useNewUrlParser: true,
useUnifiedTopology: true
}
);
return console.log("Database connected!");
} catch (e) {
return console.log("Database error!", e.message);
}
};
这里是CodeSandbox的documentation。