Skip to content

Instantly share code, notes, and snippets.

@ernestofreyreg
Created May 15, 2017 23:10
Show Gist options
  • Save ernestofreyreg/8fedcc183257a529396cc479e3ed8e48 to your computer and use it in GitHub Desktop.
Save ernestofreyreg/8fedcc183257a529396cc479e3ed8e48 to your computer and use it in GitHub Desktop.
Create and Read contacts
require('dotenv').config()
import { MongoClient } from 'mongodb'
const connectMongoDB = () => MongoClient.connect(process.env.MONGODB)
const getContacts = (req, res) => {
return connectMongoDB()
.then(
db => db.collection('contacts')
.find({})
.toArray()
.then(documents => ({db, documents}))
)
.then(({db, documents}) => {
db.close()
return documents
})
.then(contacts => res.json(contacts))
.catch(err => res.status(400).send(err.toString()))
}
const createContact = (req, res) => {
return connectMongoDB()
.then(
db => db.collection('contacts').insertOne(req.body)
.then(result => db)
)
.then(db => db.close())
.then(() => res.json({result: 'ok'}))
.catch(err => res.status(400).send(err.toString()))
}
export const handler = (req, res) => {
if (req.method === 'POST') {
return createContact(req, res)
}
return getContacts(req, res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment