美文网首页
nodejs mongodb

nodejs mongodb

作者: 自由快挂 | 来源:发表于2017-12-08 11:25 被阅读18次

    https://zellwk.com/blog/crud-express-mongodb/

    有两个过期的地方:

    1. MongoDB 在线服务网站 https://mlab.com 500M 免费空间,好测试。
    2. 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('/');
        });
    })
    

    相关文章

      网友评论

          本文标题:nodejs mongodb

          本文链接:https://www.haomeiwen.com/subject/nvqeixtx.html