MongoDB Notes

Soumyadip
The Dev Newbie
2 min readOct 23, 2020

--

Adding MongoDB

Add this to install Mongoose for MongoDB first:

npm install --save mongoose

Install Multer for Image upload

npm install --save multer

Importing and using Mongoose

To import Mongoose, first create a variable in a post.js file as follows:

const mongoose = require('mongoose');

To make a new schema:

const postSchema = mongoose.Schema({*Input Schema*});

Instead of Input Schema we add the types and names of the inputs that we are expecting to receive.

Making Models

Schemas are really just blueprints. We need some actual ‘thing’ to work with in our code. Thus, we use Models.

To make a model:

module.exports = mongoose.model('*Model Name*', *Schema name*);

Instead of Model Name and Schema Name, we use the model name that we want to use and the schema that model should have, respectively.

Using Models

When we need to use the database to fetch or post data, we change in the server.

Import the model:

const Post = require('*File Location of Model*');

Add in the app.use:

const post = new *Model name*({*Inputs here*});

Also, import the mongoose:

const mongoose = require('mongoose');

Using Cloud DBs

Go to https://cloud.mongodb.com/ and register by username to get a free database. To add this cloud database to your app, simply click ‘connect’ on the website, then fill in desired options and they will present you with a link. This link needs to be imported with Mongoose, in the Server as:

mongoose.connect("*copied link with username and password*");

It is very simple to save the input stuff from the server to the cloud database, simply type:

*Model name*.save();

To fetch the data from the database, we use in the server:

*Model name*.find().then(documents => {*What you want to do with data*});

To delete the data from the database, we first add in the server:

app.delete("/api/*Collection name*:id", (req,res,next) => {*content below.*})

To delete the data from the database, we use in the app.delete:

*Model name*.deleteOne({.id: req.params.id});

Image Upload

Inject multer:

const multer = require('multer');

--

--

Soumyadip
The Dev Newbie

HTML, CSS, Angular and Java amateur at 16 years old. Is also learning UI/UX design as an encore.