Skip to content

Instantly share code, notes, and snippets.

@raditotev
Created January 9, 2022 09:05
Show Gist options
  • Save raditotev/5e985d85bf3bb90b979d46575dd94438 to your computer and use it in GitHub Desktop.
Save raditotev/5e985d85bf3bb90b979d46575dd94438 to your computer and use it in GitHub Desktop.
Step by step guide to connecting and interacting with mongo db

Mongo, Mongoose

  • Install mongoose - npm install mongoose
  • Create connection in app.js using your db credentials
// app.js
const mongoose = require('mongoose');

mongoose
  .connect('mongodb://localhost/my_database')
  .then(() => {
    app.listen(PORT || 3000);
  })
  .catch((error) => {
    console.log(error);
  });
  • Place you DB secrets in a a nodemon.json, .env or similar file and use the process.env to pass your credentials. Don't forget to add the file with your secrets in .gitignore.

  • Create models folder in the root of your project.

  • Add your resource model. If your resource is Product for example, your model might look like:

    // models/product.js
    const { Schema, model } = require('mongoose');
    
    const productSchema = new Schema({
      name: { type: String, required: true },
      price: { type: Number, required: true },
    });
    
    module.exports = model('Product', productSchema);
  • If you create a model that has a relation with another resource, you should link them. Take a resource Order for example, related to Product:

    // models/order.js
    const { Schema, Types, model } = require('mongoose');
    
    const orderSchema = new Schema({
      quantity: { type: Number, required: true },
      product: { type: Types.ObjectId, required: true, ref: 'Product' },
    });
    
    module.exports = model('Order', orderSchema);

    If the relationship is with a multiple documents of the other model it should be defined as follows:

    const orderSchema = new Schema({
      products: [{ type: Types.ObjectId, required: true, ref: 'Product' }],
    });
  • After your model is defined you can use it to interact with your DB.

    // routes/products.js
    
    ...
    
    const Product = require('../models/product');
    
    // Get all products
    router.get('/', async (req, res, next) => {
      try {
        const products = await Product.find();
        res.status(200).json({ message: 'Get all products', products });
      } catch (error) {
        console.log(error);
        next(createError(502, error.message));
      }
    });
    
    // Create new product
    router.post('/', async (req, res, next) => {
      const { name, price } = req.body;
      const product = new Product({
        name,
        price,
      });
    
      try {
        await product.save();
        res.status(201).json({ message: 'Created a new product', product });
      } catch (error) {
        console.log(error);
        next(createError(502, error.message));
      }
    });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment