
nodejs – start project with mongodb for cyclic.sh
Table of Contents
Source
git --version
npm --version
node --version
npm init -y
npm i express mongoose dotenv
NOTE: Enter Directory Tree
npm install --save-dev nodemon
// add to package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js",
"dev": "nodemon index.js"
//index.js
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const Book = require("./models/books");
const app = express();
const PORT = process.nextTick.PORT || 3000;
mongoose.set("strictQuery", false);
const connectDB = async () => {
try {
const conn = await mongoose.mongoose.connect(process.env.MONGO_URI);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.log(error);
process.exit(1);
}
};
app.get("/", (req, res) => {
res.send({ title: "book" });
});
connectDB().then(() => {
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
});
app.get("/add-books", async (req, res) => {
try {
await Book.insertMany([
{
title: "TestTitle",
body: "TestBody",
},
{
title: "Big",
body: "Balls",
},
]);
res.send("Books send");
} catch (error) {
console.log("err: " + error);
}
});
app.get("/books", async (req, res) => {
const book = await Book.find();
if (book) {
res.json(book);
} else {
res.send("Something went wrong.");
}
});
// books
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BookSchema = new Schema({
title: {
type: String,
require: true,
},
body: {
type: String,
require: true,
}
});
module.exports = mongoose.model('Book', BookSchema);
//.env
MONGO_URI = mongodb+srv://:@cluster0.yourcluster.mongodb.net/test