https://zellwk.com/blog/crud-express-mongodb/
有两个过期的地方:
- MongoDB 在线服务网站 https://mlab.com 500M 免费空间,好测试。
- MongoClient.connect 的回调返回值, db => client (SO 上找解决方案)
console.log('May Node be with you')
var express = require ('express');
var bodyParser = require ('body-parser')
var app = express();
var db;
var MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb://<dbuser>:<dbpassword>@ds133746.mlab.com:33746/hello', { native_parser: true }, function (err, client) {
if (err) return console.log(err);
db = client.db('hello');
app.listen(3000, function () {
console.log('l on http://localhost:3000');
})
})
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
})
app.post('/quotes', function (req, res) {
console.log(req.body);
db.collection('quotes').save(req.body, function (err, result) {
if (err) {
console.log('save db err');
return console.log(err);
}
console.log('save to db');
res.redirect('/');
});
})
网友评论