You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// import mongooseconstmongoose=require("mongoose")// read your .envrequire("dotenv").config()// GET YOUR DATABASE_URL VARIABLE FROM YOU .ENV - mongodb://username:[email protected]/mydatabasenameconstDATABASE_URL=process.env.DATABASE_URL// Connect to Mongomongoose.connect(DATABASE_URL)// Database Messages so we can monitor connection statusmongoose.connection.on("connected",()=>console.log("connected to mongodb"))// message when connection established.on("closed",()=>console.log("disconnected from mongodb"))// message when connection closed.on("error",(error)=>console.log(error))// log error if error connecting// export the connection to use in other filesmodule.exports=mongoose
Writing a Mongoose Model
constmongoose=require('./connection.js');// importing the exported mongoose from previous code snippetconstSchema=mongoose.Schema;// Create a Schema for a ToDo item// describes each property inside of a TodoconsttoDoSchema=newSchema({title: {type: String,required: true},description: {type: String,default: ''},completed: {type: Boolean,default: false},dueDate: {type: Date,default: null},createdAt: {type: Date,default: Date.now}});// Create a Model from the SchemaconstToDo=mongoose.model('ToDo',toDoSchema);// export the model for use in other filesmodule.exports=ToDo;
Using the Async/Await Syntax
constexpress=require('express');constrouter=express.Router();constToDo=require('./models/todo');// Assuming your model is saved in models/todo.js// INDEX - Show all Todosrouter.get('/todos',async(req,res)=>{try{consttodos=awaitToDo.find({});res.render('todos/index.ejs',{todos: todos});}catch(err){console.log(err);res.redirect('/');}});// NEW - Show form to create new Todorouter.get('/todos/new',(req,res)=>{res.render('todos/new.ejs');});// CREATE - Add new Todo to DBrouter.post('/todos',async(req,res)=>{try{awaitToDo.create(req.body);res.redirect('/todos');}catch(err){console.log(err);res.render('todos/new.ejs');}});// SHOW - Shows more info about one Todorouter.get('/todos/:id',async(req,res)=>{try{constfoundTodo=awaitToDo.findById(req.params.id);res.render('todos/show.ejs',{todo: foundTodo});}catch(err){console.log(err);res.redirect('/todos');}});// EDIT - Show edit form for one Todorouter.get('/todos/:id/edit',async(req,res)=>{try{constfoundTodo=awaitToDo.findById(req.params.id);res.render('todos/edit.ejs',{todo: foundTodo});}catch(err){console.log(err);res.redirect('/todos');}});// UPDATE - Update a particular Todo, then redirect somewhererouter.put('/todos/:id',async(req,res)=>{try{awaitToDo.findByIdAndUpdate(req.params.id,req.body);res.redirect('/todos/'+req.params.id);}catch(err){console.log(err);res.redirect('/todos');}});// DELETE - Delete a particular Todo, then redirect somewhererouter.delete('/todos/:id',async(req,res)=>{try{awaitToDo.findByIdAndRemove(req.params.id);res.redirect('/todos');}catch(err){console.log(err);res.redirect('/todos');}});module.exports=router;
Using the Promise .then Syntax
constexpress=require('express');constrouter=express.Router();constToDo=require('./models/todo');// Assuming your model is saved in models/todo.js// INDEX - Show all Todosrouter.get('/todos',(req,res)=>{ToDo.find({}).then(todos=>{res.render('todos/index.ejs',{todos: todos});}).catch(err=>{console.log(err);res.redirect('/');});});// NEW - Show form to create new Todorouter.get('/todos/new',(req,res)=>{res.render('todos/new.ejs');});// CREATE - Add new Todo to DBrouter.post('/todos',(req,res)=>{ToDo.create(req.body).then(newTodo=>{res.redirect('/todos');}).catch(err=>{console.log(err);res.render('todos/new.ejs');});});// SHOW - Shows more info about one Todorouter.get('/todos/:id',(req,res)=>{ToDo.findById(req.params.id).then(foundTodo=>{res.render('todos/show.ejs',{todo: foundTodo});}).catch(err=>{console.log(err);res.redirect('/todos');});});// EDIT - Show edit form for one Todorouter.get('/todos/:id/edit',(req,res)=>{ToDo.findById(req.params.id).then(foundTodo=>{res.render('todos/edit.ejs',{todo: foundTodo});}).catch(err=>{console.log(err);res.redirect('/todos');});});// UPDATE - Update a particular Todo, then redirect somewhererouter.put('/todos/:id',(req,res)=>{ToDo.findByIdAndUpdate(req.params.id,req.body).then(updatedTodo=>{res.redirect('/todos/'+req.params.id);}).catch(err=>{console.log(err);res.redirect('/todos');});});// DELETE - Delete a particular Todo, then redirect somewhererouter.delete('/todos/:id',(req,res)=>{ToDo.findByIdAndRemove(req.params.id).then(()=>{res.redirect('/todos');}).catch(err=>{console.log(err);res.redirect('/todos');});});module.exports=router;
Mongoose Events
constmongoose=require('mongoose');// Replace with your MongoDB connection stringconsturi='your_mongodb_connection_string';mongoose.connect(uri,{useNewUrlParser: true,useUnifiedTopology: true});constdb=mongoose.connection;// Event when the connection is successfully openeddb.on('open',()=>{console.log('Connection to MongoDB established successfully.');});// Event for connection errorsdb.on('error',(err)=>{console.error('Connection error:',err.message);});// Event when the connection is disconnecteddb.on('disconnected',()=>{console.log('Mongoose connection disconnected.');});// Event when the connection is reconnecteddb.on('reconnected',()=>{console.log('Mongoose reconnected to the database.');});// Event when the connection is closeddb.on('close',()=>{console.log('Mongoose connection closed.');});// Event when a connection timeout occursdb.on('timeout',(e)=>{console.warn('Mongoose connection timeout:',e);});// Event when the connection is ready to usedb.once('connected',()=>{console.log('Mongoose connection is ready.');});// Optional: Event for debugging purposesmongoose.set('debug',(collectionName,method,query,doc)=>{console.log(`${collectionName}.${method}`,JSON.stringify(query),doc);});
CRUD Routes using Callback Syntax (Deprecated as of Mongoose 7.0)
constexpress=require('express');constrouter=express.Router();constToDo=require('./models/todo');// Assuming your model is saved in models/todo.js// INDEX - Show all Todosrouter.get('/todos',(req,res)=>{ToDo.find({},(err,todos)=>{if(err){console.log(err);res.redirect('/');}else{res.render('todos/index.ejs',{todos: todos});}});});// NEW - Show form to create new Todorouter.get('/todos/new',(req,res)=>{res.render('todos/new.ejs');});// CREATE - Add new Todo to DBrouter.post('/todos',(req,res)=>{ToDo.create(req.body.todo,(err,newTodo)=>{if(err){res.render('todos/new');}else{res.redirect('/todos');}});});// SHOW - Shows more info about one Todorouter.get('/todos/:id',(req,res)=>{ToDo.findById(req.params.id,(err,foundTodo)=>{if(err){res.redirect('/todos');}else{res.render('todos/show.ejs',{todo: foundTodo});}});});// EDIT - Show edit form for one Todorouter.get('/todos/:id/edit',(req,res)=>{ToDo.findById(req.params.id,(err,foundTodo)=>{if(err){res.redirect('/todos');}else{res.render('todos/edit.ejs',{todo: foundTodo});}});});// UPDATE - Update a particular Todo, then redirect somewhererouter.put('/todos/:id',(req,res)=>{ToDo.findByIdAndUpdate(req.params.id,req.body.todo,(err,updatedTodo)=>{if(err){res.redirect('/todos');}else{res.redirect('/todos/'+req.params.id);}});});// DELETE - Delete a particular Todo, then redirect somewhererouter.delete('/todos/:id',(req,res)=>{ToDo.findByIdAndRemove(req.params.id,(err)=>{if(err){res.redirect('/todos');}else{res.redirect('/todos');}});});module.exports=router;