0

I have been following an Udemy course to learn mongodb, and since the tutor uses a cloud based ide (cloud9), I have also decided to use the same. However, since cloud9 now requires AWS account I thought of using CodeSandbox. But I can't figure out how to start Mongo server on it. After installing both Mongod and MongoDB, if I try to run the app.js, it gives me error:

    (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.

If I try to run mongod, it says

mongod: command not found

This is my app.js

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");

mongoose.connect("mongodb://localhost/yelp_camp");

I have tried installing mongo and mongod using codesandbox's UI , using terminal (npm install), and doing what cloud9's docs say (I know it should not work but I can't find any Codesandbox documentation)

Is it possible to do this in codesandbox or will I have to use MongoAtlas? Thanks in advance!

3 Answers3

2

I think there's no database hosting on CodeSandbox, so you should use an external service.

Some services you can use:

MLab example

  1. Set up a database at MLab
  2. Copy and paste the connection string

A simple example function would be:

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);
  }
};

Here's the documentation of CodeSandbox.

Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
1

CodeSandbox has a starter for connecting to hosted MongoDB like Atlas - see https://codesandbox.io/s/mongodb-database-example-starter-v3ker

Gareth
  • 117
  • 4
1

While the other answers are true you may want to look into using an in-memory version of mongodb from the great mongodb-memory-server. This will prevent you from leaking any secrets like DB passwords, etc. that are in something like an atlas query string.

Here's a really simple example using typescript, mongoose, and mongodb that I just made for this answer (note that mongoose can be removed and you can use the native MongoDB driver instead.)

Here's the relevant code from the sandbox.

import { MongoMemoryServer } from "mongodb-memory-server";
import mongoose from "mongoose";

const Book = new mongoose.Schema({
  title: String,
  author: String,
});

const BookModel = mongoose.model("Book", Book);

async function bootstrap() {
  // This will create an new instance of "MongoMemoryServer" and automatically start it
  const mongod = await MongoMemoryServer.create();

  const uri = mongod.getUri();

  await mongoose.connect(uri);
}

// Could be in an index.ts file
bootstrap().then(async function () {
  // Seeding the database so there are some entries this is not necessary in production apps:

  await BookModel.create({
    title: "The Hunger Games",
    author: "Suzanne Collins",
  });

  await BookModel.create({
    title: "The Great Gatsby",
    author: "F. Scott Fitzgerald",
  });

  await BookModel.create({
    title: "Pride and Prejudice",
    author: "Jane Austen",
  });

  const book = await BookModel.find({ title: /The/i });

  console.log(book);
});
John
  • 7,114
  • 2
  • 37
  • 57