类型错误:db.collection 不是函数 [英] TypeError: db.collection is not a function
问题描述
我正在尝试将数据发布到我在 mLab 上创建的数据库中,但我收到此错误,但我不知道出了什么问题.我也已阅读有关此主题的先前提出的问题,但我无法解决我的错误,因为我是新手.所以在这里我发布了我试图实现的代码,它取自本教程 https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2.
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
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 中,你传递了一个空对象,你需要将数据库作为第二个参数传递给它你的 routes/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);
});
});
这篇关于类型错误:db.collection 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!