0% found this document useful (0 votes)
161 views22 pages

MongoDB - Building A Simple CRUD Application With Express and MongoDB

This document outlines the steps to build a simple CRUD (create, read, update, delete) application using Express and MongoDB. It shows how to initialize the project, connect to a MongoDB database, create routes to handle form submission and display data, and use EJS templates to render the user interface. Key aspects covered include initializing NPM, installing dependencies like Express, body-parser and MongoDB, defining routes, connecting to MongoDB using MongoClient, saving and finding data from collections, and rendering views with data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
161 views22 pages

MongoDB - Building A Simple CRUD Application With Express and MongoDB

This document outlines the steps to build a simple CRUD (create, read, update, delete) application using Express and MongoDB. It shows how to initialize the project, connect to a MongoDB database, create routes to handle form submission and display data, and use EJS templates to render the user interface. Key aspects covered include initializing NPM, installing dependencies like Express, body-parser and MongoDB, defining routes, connecting to MongoDB using MongoClient, saving and finding data from collections, and rendering views with data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Building a Simple CRUD Application with Express and MongoDB | Ze...

1 de 22

http://zellwk.com/blog/crud-express-mongodb/

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

2 de 22

http://zellwk.com/blog/crud-express-mongodb/

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

3 de 22

http://zellwk.com/blog/crud-express-mongodb/

$ node -v

npm init
package.json

$ npm init

node

server.js

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

4 de 22

http://zellwk.com/blog/crud-express-mongodb/

$ touch server.js

server.js

console.log

server.js

console.log('May Node be with you')

node server.js

npm install express --save

$ npm install express --save

package.json

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

5 de 22

http://zellwk.com/blog/crud-express-mongodb/

server.js

const express = require('express');


const app = express();

listen

app.listen(3000, function() {
})

console.log('listening on 3000')

node server.js

localhost:3000

get

app.get(path, callback)

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

6 de 22

http://zellwk.com/blog/crud-express-mongodb/

path

localhost:3000

localhost:3000/

app.get('/', function (request, response) {


})

// do something here

send

app.get('/', function(req, res) {


})

res.send('Hello World')

// Note: request and response are usually written as req and res respectively.

function()

app.get('/', (req, res) => {


})

res.send('hello world')

CTRL + C
node server.js
localhost:3000

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

7 de 22

http://zellwk.com/blog/crud-express-mongodb/

index.html

sendFile

res

app.get('/', (req, res) => {

res.sendFile(__dirname + '/index.html')

// Note: __dirname is the path to your current working directory. Try logging it

and see what you get!


})

// Mine was '/Users/zellwk/Projects/demo-repos/crud-express-mongo' for this app.

sendFile

index.html

touch index.html

index.html

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">
<title>MY APP</title>

</head>
<body>

May Node and Express be with you.

</body>
</html>

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

8 de 22

http://zellwk.com/blog/crud-express-mongodb/

server.js

$ npm install nodemon --save-dev

--save-dev
devDependency

package.json

nodemon server.js

-g

node_modules

$ ./node_modules/.bin/nodemon server.js

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

9 de 22

http://zellwk.com/blog/crud-express-mongodb/
script

package.json

// ...

"scripts": {
}

"dev": "nodemon server.js"

// ...

npm run dev

nodemon server.js

<form>
<form>

<form>

index.html
action
method
name

<input

<form action="/quotes" method="POST">

<input type="text" placeholder="name" name="name">

<input type="text" placeholder="quote" name="quote">


<button type="submit">Submit</button>

</form>

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

10 de 22

action

http://zellwk.com/blog/crud-express-mongodb/

/quotes

method

post

app.post('/quotes', (req, res) => {


})

console.log('Hellooooooooooooooooo!')

Hellooooooooooooooooo!

<form>

$ npm install body-parser --save

use

const express = require('express')

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

11 de 22

http://zellwk.com/blog/crud-express-mongodb/

const bodyParser= require('body-parser')


const app = express()

app.use(bodyParser.urlencoded({extended: true}))
// All your handlers here...

urlencoded

<form>

req.body

body

request

console.log

app.post('/quotes', (req, res) => {


})

console.log(req.body)

npm install mongodb --save

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

12 de 22

http://zellwk.com/blog/crud-express-mongodb/
Mongo.Client

const MongoClient = require('mongodb').MongoClient


MongoClient.connect('link-to-mongodb', (err, database) => {
})

// ... start the server

sandbox

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

13 de 22

http://zellwk.com/blog/crud-express-mongodb/

MongoClient.connect

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

14 de 22

http://zellwk.com/blog/crud-express-mongodb/

MongoClient.connect('your-mongodb-url', (err, database) => {


})

// ... do something here

app.listen

db

connect

var db
MongoClient.connect('your-mongodb-url', (err, database) => {
if (err) return console.log(err)
db = database

app.listen(3000, () => {

})

})

console.log('listening on 3000')

quotes

quotes

quotes

db.collection()

save

app.post('/quotes', (req, res) => {

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

15 de 22

http://zellwk.com/blog/crud-express-mongodb/

db.collection('quotes').save(req.body, (err, result) => {


if (err) return console.log(err)

console.log('saved to database')

})

})

res.redirect('/')

<form>

collection

find

app.get('/', (req, res) => {

var cursor = db.collection('quotes').find()

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

16 de 22

http://zellwk.com/blog/crud-express-mongodb/

})

find

cursor

console.log

cursor
toArray
toArray

console.log()

db.collection('quotes').find().toArray(function(err, results) {
console.log(results)

})

// send HTML file populated with quotes here

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

17 de 22

http://zellwk.com/blog/crud-express-mongodb/

index.html

ejs

view engine

ejs

$ npm install ejs --save

app.set('view engine', 'ejs')

view engine
response

render

render

res.render(view, locals)

views

views

index.ejs

views

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

18 de 22

http://zellwk.com/blog/crud-express-mongodb/

mkdir views

touch views/index.ejs

index.ejs

<ul class="quotes">

<% for(var i=0; i<quotes.length; i++) {%>


<li class="quote">

<span><%= quotes[i].name %></span>

<span><%= quotes[i].quote %></span>

</li>

<% } %>

</ul>

<%=

<%

%>

%>

quotes[i].name

<form>

index.ejs

quotes[i].quote

index.html

quotes

index.ejs

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">
<title>MY APP</title>

</head>
<body>

May Node and Express be with you.

<ul class="quotes">

<% for(var i=0; i<quotes.length; i++) {%>


<li class="quote">

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

19 de 22

http://zellwk.com/blog/crud-express-mongodb/

<span><%= quotes[i].name %></span>

<span><%= quotes[i].quote %></span>

</li>

<% } %>
</ul>

<form action="/quotes" method="POST">

<input type="text" placeholder="name" name="name">

<input type="text" placeholder="quote" name="quote">


<button type="submit">Submit</button>

</form>

</body>
</html>

index.ejs
index.ejs

quotes

app.get('/', (req, res) => {

db.collection('quotes').find().toArray((err, result) => {


if (err) return console.log(err)
// renders index.ejs

})

})

res.render('index.ejs', {quotes: result})

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

20 de 22

http://zellwk.com/blog/crud-express-mongodb/

26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

21 de 22

53 Comments

http://zellwk.com/blog/crud-express-mongodb/

Zell's Blog

Recommend 14

Login

Sort by Newest

Share

Join the discussion


Absay 11 days ago

In case you're wondering, here's the complete code:


const express = require('express');

const MongoClient = require('mongodb').MongoClient


const bodyParser= require('body-parser');
const app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
var db;

MongoClient.connect('mongodb://127.0.0.1:27017/{your database}', (err, database) => {


if (err) return console.log(err)

db = database

app.listen(3000, () => {

console.log('listening on 3000')

})

})

Reply Share

see more

Deepak Naik 15 days ago

Thanks a lot ! I wish all the documentations / walkthroughs should be crystal clear
like this.
Reply Share

Ryan Garant 17 days ago

Super helpful! This helped fill in a lot of gaps in my mind about how this all fits
together! Still have some ways to go though ;)
Reply Share

cbstodd 19 days ago

How would you connect to mongodb using mongoose and a local instance?
Can I use the same MongoClient function and just add my mongoose.connect
instead?
***UPDATE*** if anyone is trying to use a local instance of MongoDB with
mongoose, you can connect using:
26/08/2016 13:58

Building a Simple CRUD Application with Express and MongoDB | Ze...

22 de 22

http://zellwk.com/blog/crud-express-mongodb/

26/08/2016 13:58

You might also like