Created
May 17, 2017 06:58
-
-
Save ernestofreyreg/022543d5b1274dea01adf824cde4929a to your computer and use it in GitHub Desktop.
MongoDB read and create backend api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('dotenv').config() | |
const { MongoClient } = require('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())) | |
} | |
module.exports.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