如何连接到Mlab mongoDB并使用基于Express的api发送数据?

时间:2018-11-06 08:02:27

标签: node.js mongodb express postman mlab

所以我要基于apiexpressJS创建一个MongoDB。我相信我的架构可以正常工作,但是在尝试通过postman发布数据时确实遇到了问题。它返回这个:

基本上,我的api非常基本,由3个主要文件组成:

index.js

const routes = require('./routes');

module.exports = function (app, db) {
    routes(app, db)
};

route.js

module.exports = function (app, db) {


    app.post('/notes', (req, res) => {
        const notes = {text: req.body.body , title: req.body.title};
        db.collection('notes').insert(notes, (err, results) => {
            if (err) {
                res.send({'error': 'An error has occured'})
            } else {
                res.send(results.ops[0]);
            }
        })
    })
};

server.js

    const express = require('express');
    const MongoClient = require('mongodb').MongoClient;
    const bodyParser = require('body-parser');
    const app = express();

    const db = require('./config/db');

    const port = 8000;


    app.use(bodyParser.urlencoded({extended : true}));
 MongoClient.connect(db.url, { useNewUrlParser: true }, (err, database) => {
        if (err) {
            return console.log(err);
        }
    require('./app/routes')(app, {});
        app.listen(port, () => {
            console.log('we are live on ' + port)
        });
    });

现在,当我使用邮递员通过x-www-form-urlencoded发送一些数据来测试api时,节点服务器会抛出此错误:

TypeError: db.collection is not a function
at app.post (/Users/gdiop/Desktop/locator/app/routes/routes.js:6:12)
at Layer.handle [as handle_request] (/Users/gdiop/Desktop/locator/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/gdiop/Desktop/locator/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/gdiop/Desktop/locator/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/gdiop/Desktop/locator/node_modules/express/lib/router/layer.js:95:5)
at /Users/gdiop/Desktop/locator/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/gdiop/Desktop/locator/node_modules/express/lib/router/index.js:335:12)
at next (/Users/gdiop/Desktop/locator/node_modules/express/lib/router/index.js:275:10)
at /Users/gdiop/Desktop/locator/node_modules/body-parser/lib/read.js:130:5
at invokeCallback (/Users/gdiop/Desktop/locator/node_modules/raw-body/index.js:224:16)

我做错了什么或我想念什么?

0 个答案:

没有答案