TypeError:db.collection不是函数 [英] TypeError: db.collection is not a function

查看:73
本文介绍了TypeError:db.collection不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将数据发布到我在mLab上创建的数据库中,但出现此错误,但我不知道出了什么问题.我也阅读了有关此主题的先前询问的问题,但无法解决我的错误,因为我是新来的.所以我在这里发布了我要实现的代码,该代码取自本教程

I am trying to post data to database that I have created on mLab and I am getting this error but I don't know whats going wrong.I also have read previously asked question on this topic but I am not able to solve my error as I am new to this. So here I am posting the code which I am trying to implement and It is taken from this tutorial https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2.

server.js

server.js

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

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


const app = express();

const port = 8000;

app.use(bodyParser.urlencoded({extened:true}));


MongoClient.connect(db.url,(err,database) =>{

    if (err) return console.log(err)
    require('./app/routes')(app,{});
    app.listen(port,() => {
        console.log("We are live on"+port); 
    });

})

db.js

module.exports = {
  url : "mongodb://JayTanna:Jay12345@ds147510.mlab.com:47510/testing"
};

index.js

const noteroutes = require('./note_routes');

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

};

note_routes.js

note_routes.js

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

推荐答案

在server.js中,您传递了空对象,您需要在该对象中传递数据库作为路由/index.js导出函数期望的第二个参数.

In your server.js, you are passing empty object where you need to pass database as second argument as its what your routes/index.js export function expects.

PFB更新了server.js:

PFB updated server.js :

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

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

const app = express();

const port = 8000;

app.use(bodyParser.urlencoded({extended:true}));

MongoClient.connect(db.url,(err,database) =>{

    if (err) return console.log(err)
    //require('./app/routes')(app,{});
    //check below line changed
     require('./app/routes')(app, database);
    app.listen(port,() => {
        console.log("We are live on"+port); 
    });

});

这篇关于TypeError:db.collection不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆