gpt4 book ai didi

node.js - Node js 和 mongoDB - TypeError : db. 集合不是函数

转载 作者:可可西里 更新时间:2023-11-01 09:33:59 24 4
gpt4 key购买 nike

我正在尝试将数据从 POSTMAN 发布到我在 mLab 上创建的外部数据库,但我收到错误 db.collection is not a function。

有一个类似的问题线程,但答案不完整,并且没有将我放入 postman 的任何键/值保存到 mLab。我尝试使用的代码来自本教程:https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2

我的代码:

服务器.js

const express  = require('express'); // Load routes application
const MongoClient = require('mongodb').MongoClient; //Load database connection application
const db = require('./config/db');
const app = express(); // Assign express app a variable
const port = 8000; //Set local port value for server
const bodyParser = require('body-parser'); // **This has to come BEFORE routes
var assert = require('assert'); // ?
var databaseURL ='mongodb://external:api@ds123312.mlab.com:23312/soundfactory';


app.listen(port, () => {
console.log('')
console.log('We are live on ' + port);
console.log('')
});


MongoClient.connect(databaseURL, function(err, db) {
assert.equal(null, err);
console.log("API has succesfully connected to Sound Facotry mlab external database.");
console.log('')
db.close();
});


app.use(bodyParser.urlencoded({ extended: true }))
require('./app/routes')(app, {}); //Must come AFTER express w/ body parser

db.js

module.exports = {
url : 'mongodb://external:api@ds123312.mlab.com:23312/soundfactory'
};

索引.js

const noteroutes = require('./note_routes');
module.exports = function(app,db)
{
noteroutes(app,db);
};

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(部分工作的代码并且不会像我的原始 server.js 文件那样抛出 db.collections 错误)

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,{});
//check below line changed
require('./app/routes')(app, database);
app.listen(port,() => {
console.log("We are live on"+port);
});
})

最佳答案

删除 node_modules 文件夹并更改 package.json 的 mongodb 版本

"mongodb": "^2.2.33"

并运行以下代码:

npm install

关于node.js - Node js 和 mongoDB - TypeError : db. 集合不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44600957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com