├── app ├── config │ └── db.config.js ├── models │ ├── index.js │ └── tutorials.model.js ├── routes │ └── tutorials.routes.js └── controllers │ └── tutorials.controller.js ├── README.md ├── package.json ├── server.js ├── LICENSE └── .gitignore /app/config/db.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | url: "mongodb://localhost:27017/my_db" 3 | }; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Node.js-Express-MongoDb-CURD 2 | 3 | This is express.js samples. 4 | 5 | ## Node environment 6 | 7 | * node 14.17.2 8 | 9 | ## Run 10 | 11 | * npm install 12 | * npm start 13 | 14 | ## Author 15 | * Jibulya Galkin 16 | ------------------------- 17 | © 2021 All right reserved. 18 | -------------------------------------------------------------------------------- /app/models/index.js: -------------------------------------------------------------------------------- 1 | const dbConfig = require("../config/db.config.js"); 2 | const mongoose = require("mongoose"); 3 | mongoose.Promise = global.Promise; 4 | 5 | const db = {}; 6 | db.mongoose = mongoose; 7 | db.url = dbConfig.url; 8 | db.tutorials = require("./tutorials.model.js")(mongoose) 9 | 10 | module.exports = db; 11 | -------------------------------------------------------------------------------- /app/models/tutorials.model.js: -------------------------------------------------------------------------------- 1 | module.exports = mongoose => { 2 | const Tutorial = mongoose.model( 3 | "tutorial", 4 | mongoose.Schema( 5 | { 6 | title: String, 7 | description: String, 8 | published: Boolean 9 | }, 10 | { timestamps: true } 11 | ) 12 | ); 13 | 14 | return Tutorial; 15 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-express-mongodb", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start":"node server.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "cors": "^2.8.5", 14 | "express": "^4.17.1", 15 | "mongoose": "^5.13.2" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /app/routes/tutorials.routes.js: -------------------------------------------------------------------------------- 1 | module.exports = app => { 2 | const tutorials = require("../controllers/tutorials.controller.js"); 3 | 4 | var router = require("express").Router(); 5 | 6 | router.post("/" , tutorials.create); 7 | 8 | router.get("/", tutorials.findAll); 9 | 10 | router.get("/published", tutorials.findAllPublished); 11 | 12 | router.get("/:id", tutorials.findOne); 13 | 14 | router.put("/:id", tutorials.update); 15 | 16 | router.delete("/" , tutorials.deleteAll); 17 | 18 | app.use('/api/tutorials', router); 19 | } -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const cors = require("cors"); 3 | const app = express(); 4 | 5 | require("./app/routes/tutorials.routes.js")(app); 6 | 7 | var corsOptions = { 8 | origin : "http://localhost:8081" 9 | }; 10 | 11 | app.use(cors(corsOptions)) 12 | 13 | app.use(express.json()) 14 | 15 | app.use(express.urlencoded({extended:true})) 16 | const db = require("./app/models"); 17 | db.mongoose 18 | .connect(db.url, { 19 | useNewUrlParser: true, 20 | useUnifiedTopology: true 21 | }) 22 | .then(() => { 23 | console.log("Connected to the database!"); 24 | }) 25 | .catch(err => { 26 | console.log("Cannot connect to the database!", err); 27 | process.exit(); 28 | }); 29 | 30 | app.get("/" , (req, res) => { 31 | res.json({message: "Welcom to my application"}) 32 | }) 33 | 34 | const PORT = process.env.PORT||8080 35 | 36 | app.listen(PORT , () => { 37 | console.log(`Server is running on port ${PORT}.`); 38 | }) 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Jibulya 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /app/controllers/tutorials.controller.js: -------------------------------------------------------------------------------- 1 | const db = require("../models"); 2 | const Tutorial = db.tutorials; 3 | exports.create = (req, res) => { 4 | if (!req.body.title){ 5 | res.status(400).send({message:"Content can not be empty"}); 6 | return; 7 | } 8 | 9 | const tutorial = new Tutorial({ 10 | title: req.body.title, 11 | description: req.body.description, 12 | published: req.body.published?req.body.published:false 13 | }); 14 | 15 | tutorial 16 | .save(tutorial) 17 | .then(data => { 18 | res.send(data); 19 | }) 20 | .catch(err => { 21 | res.status(500).send({ 22 | message: err.message|| "Some error occured while creating the Tutorial." 23 | }); 24 | }); 25 | }; 26 | 27 | exports.findAll = (req, res) => { 28 | const title = req.query.title; 29 | var condition = title? {title: {$regex: new RegExp(title) , $options: "i"}} :{}; 30 | 31 | Tutorial.find(condition) 32 | .then(data => { 33 | res.send(data); 34 | }) 35 | .then(data => { 36 | res.send(data); 37 | }) 38 | .catch(err => { 39 | res.status(500).send({ 40 | message : err.message || "Some error occurred while retrieving tutorials" 41 | 42 | }); 43 | }); 44 | 45 | }; 46 | 47 | exports.findOne = (req, res) => { 48 | const id = req.params.id; 49 | Tutorial.findById(id) 50 | .then(data => { 51 | if(!data) 52 | res.status(400).send({message: "Not found Tutorials with id" + id}); 53 | else res.send(data); 54 | }) 55 | .catch(err => { 56 | res.status(500).send({message: "Error retrieving Tutorial with id=" + id}); 57 | 58 | }); 59 | }; 60 | 61 | exports.update = (req, res) => { 62 | if(!req.body){ 63 | return res.status(400).send({ 64 | message: "Data to update can not be empty!" 65 | }); 66 | } 67 | 68 | const id = req.params.id; 69 | 70 | Tutorial.findByIdAndUpdate(id, req.body, { useFindAnModify: false}) 71 | .then(data => { 72 | if(!data){ 73 | res.status(404).send({ 74 | message: `Cannot update Tutorials with id= ${id}. Maybe Tutorials was not found!` 75 | }); 76 | } 77 | else res.send({message: "Tutorials was updated successfully."}); 78 | }) 79 | .catch(err => { 80 | res.status(500).send({ 81 | message: "Error updating Tutorials with id=" + id 82 | }); 83 | }); 84 | 85 | }; 86 | 87 | exports.delete = (req, res) => { 88 | const id = req.params.id; 89 | 90 | Tutorial.findByIdAndRemove(id) 91 | .then(data => { 92 | if(!data){ 93 | res.status(404).send({ 94 | message: `Cannot delete Tutorial with id=${id}. Maybe Tutorials was not found ` 95 | }); 96 | } 97 | else { 98 | res.send({ 99 | message: "Tutorials was deleted successfully!" 100 | }); 101 | } 102 | }) 103 | .catch(err => { 104 | res.status(500).send({ 105 | message: "Could not delete Tutorial with id=" + id 106 | }); 107 | }); 108 | 109 | } 110 | 111 | exports.deleteAll = (req, res) => { 112 | Tutorial.deleteMany({}) 113 | .then(data => { 114 | res.send({ 115 | message: `${data.deletedCount} Tutorialls were deleted successfully` 116 | }); 117 | }) 118 | .catch(err => { 119 | res.status(500).send({ 120 | message: err.message||"Some error occured while removing all tutorials." 121 | }); 122 | }); 123 | }; 124 | 125 | exports.findAllPublished = (req, res) => { 126 | Tutorial.find({ published: true}) 127 | .then(data => { 128 | res.send(data); 129 | }) 130 | .catch(err => { 131 | res.status(500).send({ 132 | message: err.message||"Some error occured while retrieving tutorials." 133 | }); 134 | }); 135 | 136 | }; 137 | 138 | 139 | --------------------------------------------------------------------------------