Windows < 10
- Copy the path of: {...Program Files\MongoDB\Server\3.6\bin}
- Advanced System settings
- Environment variables
- System variables
- Find Path, click edit and add ; + the path from step 1
- Create Data/db folders in the root of one of your hard drives
- run cmd in that drive
- type mongod
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;