41
loading...
This website collects cookies to deliver better user experience
npm install --save mongodb
version: '3'
services:
mongo:
image: mongo
container_name: mongo
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: password
MONGO_INITDB_DATABASE: phonebook
volumes:
- ./data/init.js:/docker-entrypoint-initdb.d/init.js:ro
ports:
- 27017:27017
.sh
ou .js
e apontarmos para docker-entrypoint-initdb.d
que ele será executado. Então aqui é o lugar perfeito para incluirmos a inicialização da collection como mostrado abaixo:print('---> CONNECTING DATABASE <---');
db = db.getSiblingDB('phonebook');
print('---> CREATING COLLECTION <---');
db.createCollection('contact');
print('---> CREATING INDEX <---');
db.contact.createIndex({ name: 1 }, { unique: true })
print('---> SUCCESS TO RUN SCRIPT <---');
> docker-compose up
>
> mongo | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.js
> mongo | {"t":{"$date":"2021-04-12T19:35:18.705+00:00"},"s":"I", "c":"NETWORK", "id":22943, "ctx":"listener","msg":"Connection accepted","attr":{"remote":"127.0.0.1:38750","connectionId":3,"connectionCount":1}}
> mongo | {"t":{"$date":"2021-04-12T19:35:18.705+00:00"},"s":"I", "c":"NETWORK", "id":51800, "ctx":"conn3","msg":"client metadata","attr":{"remote":"127.0.0.1:38750","client":"conn3","doc":{"application":{"name":"MongoDB Shell"},"driver":{"name":"MongoDB Internal Client","version":"4.4.5"},"os":{"type":"Linux","name":"Ubuntu","architecture":"x86_64","version":"18.04"}}}}
> mongo | ---> CONNECTING DATABASE <---
> mongo | ---> CREATING COLLECTION <---
> mongo | {"t":{"$date":"2021-04-12T19:35:18.720+00:00"},"s":"I", "c":"STORAGE", "id":20320, "ctx":"conn3","msg":"createCollection","attr":{"namespace":"phonebook.contact","uuidDisposition":"generated","uuid":{"uuid":{"$uuid":"dfab7eaa-99b0-4b3b-9f41-07b104a27fdb"}},"options":{}}}
> mongo | {"t":{"$date":"2021-04-12T19:35:18.738+00:00"},"s":"I", "c":"INDEX", "id":20345, "ctx":"conn3","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"phonebook.contact","index":"_id_","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}}
> mongo | ---> CREATING INDEX <---
> mongo | {"t":{"$date":"2021-04-12T19:35:18.739+00:00"},"s":"I", "c":"INDEX", "id":20438, "ctx":"conn3","msg":"Index build: registering","attr":{"buildUUID":{"uuid":{"$uuid":"b8a5db18-ea67-4b2b-aad0-fe81e6f46df6"}},"namespace":"phonebook.contact","collectionUUID":{"uuid":{"$uuid":"dfab7eaa-99b0-4b3b-9f41-07b104a27fdb"}},"indexes":1,"firstIndex":{"name":"name_1"}}}
> mongo | {"t":{"$date":"2021-04-12T19:35:18.811+00:00"},"s":"I", "c":"INDEX", "id":20345, "ctx":"conn3","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"phonebook.contact","index":"name_1","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}}
> mongo | {"t":{"$date":"2021-04-12T19:35:18.812+00:00"},"s":"I", "c":"INDEX", "id":20440, "ctx":"conn3","msg":"Index build: waiting for index build to complete","attr":{"buildUUID":{"uuid":{"$uuid":"b8a5db18-ea67-4b2b-aad0-fe81e6f46df6"}},"deadline":{"$date":{"$numberLong":"9223372036854775807"}}}}
> mongo | {"t":{"$date":"2021-04-12T19:35:18.812+00:00"},"s":"I", "c":"INDEX", "id":20447, "ctx":"conn3","msg":"Index build: completed","attr":{"buildUUID":{"uuid":{"$uuid":"b8a5db18-ea67-4b2b-aad0-fe81e6f46df6"}}}}
> mongo | ---> SUCCESS TO RUN SCRIPT <---
mongo_repository.js
na pasta repository do projeto:const MongoClient = require('mongodb').MongoClient
class MongoRepository{
constructor(connectionString){
this.connectionString = connectionString
this.contactCollection = null
}
async init(){
await this._connect(this.connectionString)
}
async _connect(connectionString){
const client = await MongoClient.connect(connectionString, {useUnifiedTopology: true})
const db = client.db('phonebook')
this.contactCollection = db.collection('contact')
return this.contactCollection
}
insert(contact){
this.contactCollection.insertOne(contact)
.then(result => console.log("Dados inseridos com sucesso", result.result))
.catch(err => {throw new Error(err)})
}
async selectAll(){
return await this.contactCollection.find().toArray()
}
async selectById(name){
return await this.contactCollection.findOne({name: name})
}
async update(name, contact){
return await this.contactCollection.findOneAndUpdate(
{name: name},
{
$set: {
name: contact.name,
telephone: contact.telephone,
address: contact.address
}
},
{
upsert: true
}
)
}
remove(name){
this.contactCollection.deleteOne({name: name})
.then(result => console.log(result.result))
.catch(err => {throw new Error(err)})
}
}
module.exports = MongoRepository
const router = require('express').Router()
const MongoRepository = require('../repository/mongo_repository.js')
const Service = require('../service')
const MongoRepo = new MongoRepository('mongodb://admin:password@localhost:27017')
MongoRepo.init()
const service = new Service(MongoRepo)
router.param('name', (req, res, next, name) => {
req.name_from_param = name
next()
})
router.post('/', async (req, res) => {
const contact = req.body
service.create(contact)
res.status(201).json(contact)
})
router.get('/:name', async (req, res) => {
const id = req.name_from_param
const result = await service.getById(id)
if(result !== undefined){
res.status(200).json(result)
return
}
res.sendStatus(204)
})
router.get('/', async (req, res) => {
const result = await service.getAll()
if(result.length > 0){
res.status(200).json(result)
return
}
res.sendStatus(204)
})
router.put("/:name", async (req, res) => {
const name = req.params.name
const body = req.body
const result = await service.put(name, body)
res.status(200).json(result)
})
router.delete("/:name", async (req, res) => {
const name = req.params.name
service.remove(name)
res.sendStatus(204)
})
module.exports = router
const MongoRepository = require('../repository/mongo_repository.js')
const Service = require('../service')
const MongoRepo = new MongoRepository('mongodb://admin:password@localhost:27017')
MongoRepo.init()
const service = new Service(MongoRepo)
curl --location --request POST 'http://localhost:3000/api' \
--header 'Content-Type: application/json' \
--data-raw '{
"id": 1,
"name": "Kelly",
"telephone": "118888888",
"address": "Rua dos Bobos n 1"
}' | json_pp
{
"id": 1,
"name": "Kelly",
"telephone": "118888888",
"address": "Rua dos Bobos n 1",
"_id": "607d805caa972341ebd3e568"
}
_id
que está retornando.router.param('name', (req, res, next, name) => {
req.name_from_param = name
next()
})
router.get('/health', (req, res) => {
res.status(200).json({status: "Ok"})
})
router.get('/:name', async (req, res) => {
const id = req.name_from_param
const result = await service.getById(id)
if(result !== undefined){
res.status(200).json(result)
return
}
res.sendStatus(204)
})
router
:router.patch("/:name", async (req, res) => {
const name = req.params.name
const body = req.body
service.patch(name, body)
res.sendStatus(204)
})
patch
do Express e informamos no path que passaremos o name
como parâmetro e o body
com o objeto que conterá a atualização parcial e chamamos a service
que também deverá possuir uma função chamada patch
.service
:patch(name, body){
return this.repository.patch(name, body);
}
mongo_repository.js
no módulo repository
:async patch(name, contact){
return await Object.entries(contact).forEach(([key, value]) => {
let obj = {}
obj[key] = value
return this.contactCollection.findOneAndUpdate({name: name}, {$set: obj})
})
}
Object.entries
que itera sobre um objeto e devolve um array onde a chave é o nome do atributo e o valor é o valor daquele atributo e com isso conseguimos iterar por esse array e realizar a operação que atualizará somente os campos que informamos.curl --location --request PATCH 'http://localhost:3000/api/Kelly' \
--header 'Content-Type: application/json' \
--data-raw '{
"address": "novo endereco novo"
}'