Skip to content

Instantly share code, notes, and snippets.

@mosluce
Created July 16, 2019 13:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mosluce/4bc5a1cd777587700e8840e4242247f4 to your computer and use it in GitHub Desktop.
Save mosluce/4bc5a1cd777587700e8840e4242247f4 to your computer and use it in GitHub Desktop.
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