Skip to content

Instantly share code, notes, and snippets.

@dragonman225
Last active January 17, 2018 10:16
Show Gist options
  • Save dragonman225/5e5d527583c0c3a46f00de8c15501eba to your computer and use it in GitHub Desktop.
Save dragonman225/5e5d527583c0c3a46f00de8c15501eba to your computer and use it in GitHub Desktop.
const path = require('path')
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const mongodb = require('mongodb').MongoClient
// MongoDB Snippet
const mongodbUrl = 'mongodb://localhost:27017' // Local MongoDB Server Address
mongodb.connect(mongodbUrl, function(err, client) { // Connect to local MongoDB Server
// Use database 'test'
let db = client.db('test')
// Save data to collection 'list'
db.collection('list').save({
"name": "jason"
}, function(err, result) {
console.log(result.result);
client.close()
});
// Find data from collection 'list'
db.collection('list').find({
"name": "jason"
}).toArray(function(err, items) {
console.log(items)
client.close()
})
})
// create application/json parser
app.use(bodyParser.json())
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({
extended: false
}))
let count = 0
app.use(express.static('public'))
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'demo.html'))
})
app.get('/welcome', function(req, res) {
mongodb.connect(mongodbUrl, function(err, client) {
let db = client.db('test')
db.collection('list').find({
"name": "jason"
}).toArray(function(err, items) {
console.log(items)
res.send(items)
client.close()
})
})
})
app.get('/info', function(req, res) {
++count
console.log(count)
const info = {
name: 'rootn',
count: count
}
res.send(info)
})
app.post('/entrance', function(req, res) {
console.log('post data:')
console.log(req.body)
mongodb.connect(mongodbUrl, function(err, client) {
var db = client.db('test')
db.collection('list').save(req.body, function(err, result) {
console.log(result.result);
client.close();
});
})
res.json({"message": "ok"})
})
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment