Skip to content

Instantly share code, notes, and snippets.

@iscott
Created August 10, 2020 21:35
Show Gist options
  • Save iscott/0bf9d65dcb5ad35a7e8ab525214343e8 to your computer and use it in GitHub Desktop.
Save iscott/0bf9d65dcb5ad35a7e8ab525214343e8 to your computer and use it in GitHub Desktop.
How to access your MongoDB in a command-line node shell using mongoose

How to access your MongoDB in a command-line node shell using mongoose

To load up a node console where you can access the database:

in terminal, run node then paste in these lines:

require("dotenv").config();
// Connect to mongodb:
require("./config/database");
// Load up our models:
const User = require("./models/user");
const Score = require("./models/score");

Then you can do this to get all users:

User.find({}, (e, users) => { console.log(users) })

Advanced setup: Mongoose Shell:

To set up your own node console (npm run console): make a console.js:

require("dotenv").config();
// Lets us create our own node console/repl and prompt for JS code:
var repl = require("repl");
// Start REPL and provide custom prompt :)
var replServer = repl.start({
  prompt: "Node Console> ",
});
// Connect to mongodb:
require("./config/database");
// Load up our models:
const User = require("./models/user");
const Score = require("./models/score");
replServer.context.User = User;
replServer.context.Score = Score;
console.log("\n");
console.log("========================================");
console.log(
  "Console loaded. To get all users type: User.find({}, (e, users) => { console.log(users) })"
);
console.log("========================================");
add
"console": "node console.js"
 to package.json scripts object.
So it should look like this:
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "heroku-postbuild": "npm run build",
    "console": "node console.js"
  },

Now to run it, just type npm run console and you'll have a node REPL with your database loaded 😎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment