Skip to content

Instantly share code, notes, and snippets.

@AlexMercedCoder
Last active December 21, 2023 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexMercedCoder/484b3e3410cf98ba8556043ec08d2bdf to your computer and use it in GitHub Desktop.
Save AlexMercedCoder/484b3e3410cf98ba8556043ec08d2bdf to your computer and use it in GitHub Desktop.
Mongo-Snippets

Connecting to Mongo Server with MongooseJS

// import mongoose
const mongoose = require("mongoose")
// read your .env
require("dotenv").config()

// GET YOUR DATABASE_URL VARIABLE FROM YOU .ENV - mongodb://username:password@myhost.com/mydatabasename
const DATABASE_URL = process.env.DATABASE_URL

// Connect to Mongo
mongoose.connect(DATABASE_URL)

// Database Messages so we can monitor connection status
mongoose.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 files
module.exports = mongoose

Writing a Mongoose Model

const mongoose = require('./connection.js'); // importing the exported mongoose from previous code snippet
const Schema = mongoose.Schema;

// Create a Schema for a ToDo item
// describes each property inside of a Todo
const toDoSchema = new Schema({
    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 Schema
const ToDo = mongoose.model('ToDo', toDoSchema);

// export the model for use in other files
module.exports = ToDo;

Using the Async/Await Syntax

const express = require('express');
const router = express.Router();
const ToDo = require('./models/todo'); // Assuming your model is saved in models/todo.js

// INDEX - Show all Todos
router.get('/todos', async (req, res) => {
    try {
        const todos = await ToDo.find({});
        res.render('todos/index.ejs', { todos: todos });
    } catch (err) {
        console.log(err);
        res.redirect('/');
    }
});

// NEW - Show form to create new Todo
router.get('/todos/new', (req, res) => {
    res.render('todos/new.ejs');
});

// CREATE - Add new Todo to DB
router.post('/todos', async (req, res) => {
    try {
        await ToDo.create(req.body);
        res.redirect('/todos');
    } catch (err) {
        console.log(err);
        res.render('todos/new.ejs');
    }
});

// SHOW - Shows more info about one Todo
router.get('/todos/:id', async (req, res) => {
    try {
        const foundTodo = await ToDo.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 Todo
router.get('/todos/:id/edit', async (req, res) => {
    try {
        const foundTodo = await ToDo.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 somewhere
router.put('/todos/:id', async (req, res) => {
    try {
        await ToDo.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 somewhere
router.delete('/todos/:id', async (req, res) => {
    try {
        await ToDo.findByIdAndRemove(req.params.id);
        res.redirect('/todos');
    } catch (err) {
        console.log(err);
        res.redirect('/todos');
    }
});

module.exports = router;

Using the Promise .then Syntax

const express = require('express');
const router = express.Router();
const ToDo = require('./models/todo'); // Assuming your model is saved in models/todo.js

// INDEX - Show all Todos
router.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 Todo
router.get('/todos/new', (req, res) => {
    res.render('todos/new.ejs');
});

// CREATE - Add new Todo to DB
router.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 Todo
router.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 Todo
router.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 somewhere
router.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 somewhere
router.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

const mongoose = require('mongoose');

// Replace with your MongoDB connection string
const uri = 'your_mongodb_connection_string';

mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });

const db = mongoose.connection;

// Event when the connection is successfully opened
db.on('open', () => {
    console.log('Connection to MongoDB established successfully.');
});

// Event for connection errors
db.on('error', (err) => {
    console.error('Connection error:', err.message);
});

// Event when the connection is disconnected
db.on('disconnected', () => {
    console.log('Mongoose connection disconnected.');
});

// Event when the connection is reconnected
db.on('reconnected', () => {
    console.log('Mongoose reconnected to the database.');
});

// Event when the connection is closed
db.on('close', () => {
    console.log('Mongoose connection closed.');
});

// Event when a connection timeout occurs
db.on('timeout', (e) => {
    console.warn('Mongoose connection timeout:', e);
});

// Event when the connection is ready to use
db.once('connected', () => {
    console.log('Mongoose connection is ready.');
});

// Optional: Event for debugging purposes
mongoose.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)

const express = require('express');
const router = express.Router();
const ToDo = require('./models/todo'); // Assuming your model is saved in models/todo.js

// INDEX - Show all Todos
router.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 Todo
router.get('/todos/new', (req, res) => {
    res.render('todos/new.ejs');
});

// CREATE - Add new Todo to DB
router.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 Todo
router.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 Todo
router.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 somewhere
router.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 somewhere
router.delete('/todos/:id', (req, res) => {
    ToDo.findByIdAndRemove(req.params.id, (err) => {
        if (err) {
            res.redirect('/todos');
        } else {
            res.redirect('/todos');
        }
    });
});

module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment