Crash Course: Querying MongoDB with Mongoose: Create a CRUD Backend in Nodejs.

CRUD: it’s an entry level acronym that means: CREATE; READ; UPDATE and DELETE. It is used in Database terms to signify the four HTTP REST Methods. Basically: any HTTP request in Software Engineering will be one of these four methods (one exception: there is also PATCH; which is basically the same method as PUT).

Again: here are the four HTTP Methods and their purpose:

  • GET: Used in data retrieval from the client to the server.
  • POST: Used in adding new data to the database.
  • PUT: Used in updating existing information.
  • DELETE: As you guessed it: delete is used to delete items from the database.

Now introducing: Mongoose. Mongoose is a Node.js based ODM for MongoDB. Don’t stress the use of the acronym ODM as this stands for Object Data Modeler. Basically speaking: Mongoose is framework that allows a programmer to interact with the database. There is also the MongoDB driver for Nodejs which is featured in one of my articles . Lastly mongoose allows one to connect to MongoDB and interact with the data.

To get started with you’ll need a MongoDB account; a MongoDB string and that is all. The first step of the process is to create a new package.json file: thus initalizing a new Nodejs project.

npm init -y

Now the next step is to create the index.js file.

touch index.js

Now install the required dependencies: in this course we will be using mongoose; express and http. This should be installed in the projects home directory.

npm i express http mongoose

Now I will write the index.js file.

// Require Dependencies
let express = require('express')
let http = require('http')
let mongoose = require('mongoose')
// Connect to MongoDB with Mongoose
mongoose.conenct(process.env.mongodbString, {
useNewUrlParser: true,
useUnifiedTopology: true
}, function() {
console.log('DB Connected')})// Define app
let app = express()
// GET Route// POST Route// PUT Route// DELETE Route// Start Server
http.createServer(app).listen(8080, function() {
console.log('Server Started on PORT 8080')})

Notice how I defined the four routes. They will be filled in one by one. As for the previous code: I’m hoping the comments will suffice as explanations. If you are following along and want to start the server: simply download nodemon from npm and run nodemon in the root of you server’s directory. This is done as so:

nodemon

Using Mongoose I will create the schema. This goes in my index.js file after the mongoose.connect method. Notice how mongoose has already been installed and required.

// Schema Production
let Schema = mongoose.Schema
// Define our UserSchema
let UserSchema = new Schema({
email: String})// Model the data
let User = mongoose.model('User', UserSchema)

The GET Route

// Get all Users
app.get('/api/get/users', function(req, res) {
User.find({}, function(err, users) { if (err) {
res.json(err)
else {
res.json(users)

}
}
})
})

The POST Route:

// POST one userapp.post('/api/post/users', function(req, res) {      User.create(req.body)})

The PUT Route:

// Update one userapp.put('/api/put/users/:id', function(req, res) {      User.findOne({ "_id": req.params.id }, function(err, user) {            if (err) {
res.json(err)
else {
user.set(req.body)
user.save()
res.json("Successful PUT Request")
})
})

And finally:

The DELETE Route:

// Delete one userapp.delete('/api/delete/user/:id', function(req, res) {    User.findOne({ "_id": req.params.id }, function(err, user) {         if (err) {          res.json(err)         } else {          user.remove()
res.json("DELETE Success")
}
})
})

And thats all folks! Go ahead and run nodemon in the root of your server. You now are ready to debug with Postman!

If you like reading about coding check out some of my other posts:

These articles pertain to Full Stack Development. Find Angular 2+ book here: .

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store