0

我一直在学习 mongodb 的 Udemy 课程,由于导师使用基于云的 ide(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");

我已经尝试使用codesandbox的UI安装mongo和mongod,使用终端(npm install),并按照cloud9的文档所说的(我知道它不应该工作,但我找不到任何Codesandbox文档)

是否可以在代码沙箱中执行此操作,还是必须使用 MongoAtlas?提前致谢!

4

2 回答 2

2

我认为 CodeSandbox 上没有数据库托管,因此您应该使用外部服务。

您可以使用的一些服务:

MLab 示例

  1. 在 MLab 建立数据库
  2. 复制并粘贴连接字符串

一个简单的示例函数是:

let initMongo = async () => {
  try {
    await mongoose.connect(
      "mongodb://<dbuser>:<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 的文档

于 2020-02-08T16:12:13.277 回答
1

CodeSandbox 有一个启动器,用于连接到像 Atlas 这样的托管 MongoDB - 请参阅https://codesandbox.io/s/mongodb-database-example-starter-v3ker

于 2020-02-19T09:40:18.400 回答