Express and MongoDB

Search for a command to run...

No comments yet. Be the first to comment.
Twitter is one of the most popular social media platforms in the world, with over 330 million active users as of 2021. If you are interested in building a Twitter-like application, this tutorial will guide you through the process of building a FullSt...

Hey everyone, In this article, we will build our own Tic Tac Toe game using pure Javascript. https://youtu.be/lKe57l8sttw Code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE...

Hi everyone, In this blog, we will learn how we can create node.js functions locally and deploy them to AWS Lambda using serverless. So, let's get started. Step 1. Create an AWS Account ☁️ In order to deploy functions to AWS Lambda, you should have a...

Hey there, In this article, we are going to learn how you can upload any file to firebase storage. Uploading files to firebase storage is really easy. I would I recommend you to code along with me for better understanding. So, let's get started. Step...

Hey there, Welcome back. In this article, I would be showing you how I made a collaborative IDE with a video call. The main application of this application is that you can create a room and people can join the room. You have the ability to write mark...

Hey there, In this article, I would be teaching you how to use MongoDB with express.js and perform CRUD operations.
MongoDB is a no-SQL database. It is a general-purpose, document-based, distributed database built for modern application developers and for the cloud era.
For Example: If I have a record of 5 students, So I can say that I have 5 documents inside a collection named as students.
Note: In this tutorial, I will be using MongoDB atlas to avoid the complexities faced while installing MongoDB and it would also be easier for beginners to understand too. MongoDB Atlas is a cloud service to use mongoDb.
Head over to https://www.mongodb.com/ and create your free account to use MongoDB atlas.





There are a couple of tweaks here and there which we need to follow to get started with MongoDB Atlas.
Navigate to Database Access
Click add new database user

Navigate to Network access and click Add IP Address
Select Allow Access from anywhere and select confirm
Now, lets set up our project structure and create boilerplate code.
npm init
Run:
npm i express mongoose
Great Going, Now let's create some files and folders. For the time bear with me and create these folders. I am going to explain the working of each and file step by step.
Our Project Structure:
myProject
|
|- model
|- user.js
|- index.js
|- package.json

In the above project structure, we have created a folder model, this is the folder where we are going to keep all our schemas for different collection.
Currently, we have one, the user.js
Head over to index.js and code along with me.
const express = require('express');
const app = express()
app.get('/', (req, res) => {
res.send('Welcome to my API');
})
app.listen(9000, () => console.log('Server Started at PORT 9000'))
Connecting application to MongoDB is really simple.

2. Click on connect your application.

3. Copy the connection string

Great Now back to our code …..
const express = require('express');
const mongoose = require('mongoose');
const app = express()
app.get('/', (req, res) => {
res.send('Welcome to my API');
})
app.listen(9000, () => console.log('Server Started at PORT 9000'))
Replace the original password with <password>
const express = require('express');
const mongoose = require('mongoose');
const app = express()
mongoose.connect(
`mongodb+srv://piyushgarg:hello123@cluster0-2bghc.mongodb.net/test?retryWrites=true&w=majority`
)
.then(() => console.log('MongoDB Connect'))
.catch((err) => console.log(`Error Occured ${err}`))
app.get('/', (req, res) => {
res.send('Welcome to my API');
})
app.listen(9000, () => console.log('Server Started at PORT 9000'))
Additionally, pass the following parameters to the connect function:
Refer to https://mongoosejs.com/docs/deprecations.html for more info
{
useNewUrlParser: true,
useUnifiedTopology: true
}
const express = require('express');
const mongoose = require('mongoose');
const app = express()
mongoose.connect(
`mongodb+srv://piyushgarg:hello123@cluster0-2bghc.mongodb.net/test?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
.then(() => console.log('MongoDB Connect'))
.catch((err) => console.log(`Error Occured ${err}`))
app.get('/', (req, res) => {
res.send('Welcome to my API');
})
app.listen(9000, () => console.log('Server Started at PORT 9000'))
In this step, we would be working with the user.js inside our models folder and create a user schema.
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
email:{
type: String,
required: true,
unique: true,
},
password:{
type: String,
required: true,
},
age: {
type: Number
}
})
const user = mongoose.model('users', userSchema);
module.exports = user;
In this file, we, first of all, require the mongoose package and then use the . Schema method to create the schema. In the Schema method, we pass an object specifying our schema of the user with various properties like type, unique and required.
Finally, we create a model using mongoose. model which requires two parameters:
First: The name of the model as a string. [ users ]
Second: The user schema we created above.
In this step, we would be creating API's to perform crud operation on our DB.
Back to index.js
const express = require('express');
const mongoose = require('mongoose');
const app = express()
const User = require('./model/user');
mongoose.connect(
`mongodb+srv://piyushgarg:hello123@cluster0-2bghc.mongodb.net/test?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
.then(() => console.log('MongoDB Connect'))
.catch((err) => console.log(`Error Occured ${err}`))
app.get('/', (req, res) => {
res.send('Welcome to my API');
})
app.get('/users/all', (req, res) => {
User.find({}, (err, users) => {
if(err) return res.json(err);
return res.json(users)
})
})
app.get('/users/:id', (req, res) => {
const id = req.params.id;
User.findById(id, (err, user) => {
if(err) return res.json(err);
return res.json(user);
})
})
app.post('/user/new', (req, res) => {
const {name, email, password, age} = req.body;
const myUser = new User();
myUser.name = name;
myUser.email = email;
myUser.password = password; // Make sure you hash the passowrd;
myUser.age = age;
myUser.save()
.then(() => res.send('User inserted into db'))
.catch(err => res.send(err))
})
app.listen(9000, () => console.log('Server Started at PORT 9000'))
There is one error in code and that is we have not implemented the express.json() middleware.
Well, that’s your task.





Authentication in Nodejs using Passport.js In this article I would be teaching you authentication in nodejs using express and passport.jsmedium.com Building REST API with Node.js Build your own REST API from scratchmedium.com Top 10 visual studio code extensions 2020 Best vscode extensions to make your development smooth and powerful.medium.com Authentication in Nodejs using JSON web tokens (JWT) Hey there, In this article, we would be learning how to implement authentication in nodejs using express and JWT aka…medium.com
Github: https://github.com/piyushgarg195
Linkedin: https://www.linkedin.com/in/piyushgarg195/
Website: https://www.piyushgarg.dev/