Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fatimah - release 01 #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,20 @@
# mongodb-crud
CRUD with MongoDB
#### CRUD with MongoDB

#### List of routes:
| Route | HTTP | Description |
| ------------------ |---------------| ------------------------------ |
| /api/books | GET | Get all the books info |
| /api/books | POST | Create a new book |
| /api/books/:id | DELETE | Delete a book |
| /api/books/:id | PUT | Update a book with new info |

# Usage
### With only npm:
```
npm install
npm start
npm run dev
```

###### Access the website via `http://localhost:3000` or API via `http://localhost:3000/api`.
19 changes: 19 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const PORT = 3000
const api = require('./routes/api')

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.use('/api', api)
app.get('/', (req, res) => {
res.status(201).json({
message: 'Hello'
})
})
// server
app.listen(PORT, () => {
console.log(`Connected! on port ${PORT}`)
})
61 changes: 61 additions & 0 deletions controllers/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const books = require('../models/books')

module.exports = {
read: (req, res) => {
books.read()
.then((data) => {
res.status(201).json({
message: 'Getting all datas',
data: data
})
}).catch(err => {
res.status(400).json({
message: err.message
})
})
},

create: (req, res) => {
books.insertOne(req.body)
.then((book) => {
res.status(201).json({
message: 'Adding new book success',
book: book
})
}).catch(err => {
res.status(400).json({
message: err.message
})
})
},

update: (req, res) => {
let id = req.params.id
books.update(id, req.body)
.then(book => {
res.status(201).json({
message: 'Update Success!',
book: book
})
}).catch(err => {
res.status(400).json({
message: err.message
})
})
},

destroy: (req, res) => {
let id = req.params.id
books.deleteOne(id)
.then(book => {
res.status(201).json({
message: 'Delete success!',
book: book
})
}).catch(err => {
res.status(400).json({
message: err.message
})
})
}
}
71 changes: 71 additions & 0 deletions models/books.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const MongoClient = require('mongodb').MongoClient
const ObjectId = require('mongodb').ObjectID
// const assert = require('assert')

const url = 'mongodb://localhost:27017'

const dbName = 'library'

module.exports = {
read: () => {
return new Promise(function(resolve, reject) {
MongoClient.connect(url).then(client => {
console.log('Connected correctly to server')
const db = client.db(dbName)
const col = db.collection('books')
const docs = col.find({}).toArray()
client.close()
resolve(docs)
}).catch(err => reject(err))
})
},

insertOne: (data) => {
return new Promise(function(resolve, reject) {
MongoClient.connect(url).then(client => {
console.log('Connected correctly to server')
const db = client.db(dbName)
const col = db.collection('books')
const insert = col.insertOne(data)
const docs = col.find(data).toArray()
client.close()
resolve(docs)
}).catch(err => reject(err))
})
},

update: (id, input) => {
return new Promise(function(resolve, reject) {
MongoClient.connect(url).then(client => {
console.log('Connected correctly to server')
const db = client.db(dbName)
const col = db.collection('books')
const update = col.findOneAndUpdate({
_id: ObjectId(id)
},
{ $set: input }, {
returnOriginal: false,
sort: [['_id', 1]],
upsert: true,
returnNewDocument: true
}
)
// console.log(update)
resolve(update)
}).catch(err => reject(err))
})
},

deleteOne: (id) => {
return new Promise(function(resolve, reject) {
MongoClient.connect(url).then(client => {
console.log('Connected correctly to server')
const db = client.db(dbName)
const col = db.collection('books')
const docs = col.find({ _id: ObjectId(id) }).toArray()
const remove = col.deleteOne({ _id: ObjectId(id) })
resolve(docs)
}).catch(err => reject(err))
})
}
}
Loading