Created
July 16, 2019 13:06
-
-
Save mosluce/4bc5a1cd777587700e8840e4242247f4 to your computer and use it in GitHub Desktop.
This file contains 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
const express = require('express'); | |
const mongodb = require('mongodb'); | |
const app = express(); | |
function to(promise) { | |
if (!(promise instanceof Promise)) { | |
promise = Promise.resolve(promise); | |
} | |
return promise.then(res => [null, res]).catch(err => [err]); | |
} | |
app.get('/posts', async (req, res) => { | |
let err, client; | |
[err, client] = await to(mongodb.connect('mongodb://localhost', { useNewUrlParser: true })); | |
if (err) { | |
} | |
const db = client.db('blog'); | |
const posts = await db.collection('Post').find().limit(10).toArray(); | |
res.json({ posts: posts }); | |
}); | |
app.get('/posts/:id', async (req, res) => { | |
const client = await mongodb.connect('mongodb://localhost', { useNewUrlParser: true }); | |
const db = client.db('blog'); | |
const post = await db.collection('Post').findOne({ _id: parseInt(req.params.id) }); | |
res.json({ post: post }); | |
}); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment