Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active October 14, 2018 16:48
Show Gist options
  • Save ivankisyov/70659d4778c0489eae3d0e5456a748b5 to your computer and use it in GitHub Desktop.
Save ivankisyov/70659d4778c0489eae3d0e5456a748b5 to your computer and use it in GitHub Desktop.
MongoDB with Mongoose

MongoDB with Mongoose

Local setup

Windows < 10

  1. Copy the path of: {...Program Files\MongoDB\Server\3.6\bin}
  2. Advanced System settings
  3. Environment variables
  4. System variables
  5. Find Path, click edit and add ; + the path from step 1
  6. Create Data/db folders in the root of one of your hard drives
  7. run cmd in that drive
  8. type mongod

Inside the project folder

npm i --save mongoose

create db/index.js

const mongoose = require("mongoose");

mongoose.Promise = global.Promise;
mongoose
  .connect(
    "mongodb://localhost:27017/Todo",
    { useNewUrlParser: true }
  )
  .then(() => {
    console.log("Connected to MongoDB...");
  })
  .catch(err => {
    console.error("Could not connect to MongoDB...", err);
  });

module.exports = {
  mongoose
};

models/todo.js

const mongoose = require("mongoose");

// todo schema
const todoSchema = mongoose.Schema({
  text: {
    type: String,
    required: true,
    minlength: 3,
    trim: true
  },
  completed: {
    type: Boolean,
    default: false
  },
  completedAt: {
    type: Number,
    default: null
  }
});

// create the model based on the schema
module.exports = mongoose.model("Todo", todoSchema);

todos route

const express = require("express");
const router = express.Router();
const { mongoose } = require({path to db/index.js});
const Todo = require({path to models/todo.js});

router.post("/", (req, res) => {
  const newTodo = new Todo({
    text: req.body.text,
    completed: req.body.completed || false
  });
  newTodo
    .save()
    .then(result => {
      res.status(201).json(result);
    })
    .catch(err => {
      res.status(400).json(err);
    });
});

module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment