npm init -y
npm install express nodemon
touch app.js
npm install mongoose
Create cluster on mongodb
npm install dotenv
Create .env file, store mongoose url in .env global variable
Import and connect mongoose (process.env.VARIABLENAME)
const router = express.Router();
router.get('/', (req, res) => {
// do something here
})
module.exports = router;
const postRoute = require(‘./routes/posts’);
app.use(‘/posts’, postRoutes)
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
}
)}
module.exports = mongoose.model(‘Posts’, PostSchema);
npm install cors
const cors = require('cors');
app.use(cors())
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const Post = require(‘../models/Post’);
router.get("/", async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch (err) {
res.json({ message: err });
}
});