node.js 类型错误:db.collection 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43779323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: db.collection is not a function
提问by Jay
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.
我正在尝试将数据发布到我在 mLab 创建的数据库中,但我收到此错误,但我不知道出了什么问题。我是新来的。所以在这里我发布了我试图实现的代码,它取自本教程https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes- a07ea9e390d2。
server.js
服务器.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
数据库.js
module.exports = {
url : "mongodb://JayTanna:[email protected]:47510/testing"
};
index.js
索引.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]);
}
});
});
};
采纳答案by Mihir Bhende
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.
在您的 server.js 中,您正在传递空对象,您需要将数据库作为第二个参数传递给它的 routes/index.js 导出函数所期望的。
PFB updated server.js :
PFB 更新了 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);
});
});
回答by Jake Boomgaarden
So I voted for the answer which said to just go down to mongodb 2.2.33 because I tried it and it worked, but then I felt weird about just downgrading to fix a problem so I found the solution which allows you to keep version >= 3.0. If anyone finds this issue and their problem wasn't passing in a blank reference like the accepted answer, try this solution out.
因此,我投票支持只使用 mongodb 2.2.33 的答案,因为我尝试了它并且它有效,但是后来我对降级以解决问题感到很奇怪,所以我找到了允许您保留版本的解决方案 >= 3.0. 如果有人发现此问题并且他们的问题没有像接受的答案那样传入空白参考,请尝试此解决方案。
When you run..
当你跑..
MongoClient.connect(db.url,(err,database) =>{ }
In mongodb version >= 3.0, That databasevariable is actually the parent object of the object you are trying to access with database.collection('whatever'). To access the correct object, you need to reference your database name, for me that was by doing
在 mongodb 版本 >= 3.0 中,该database变量实际上是您尝试使用database.collection('whatever'). 要访问正确的对象,您需要引用您的数据库名称,对我来说是这样做的
MongoClient.connect(db.url,(err,database) =>{
const myAwesomeDB = database.db('myDatabaseNameAsAString')
myAwesomeDB.collection('theCollectionIwantToAccess')
}
This fixed my errors when running my node.js server, hopefully this helps somebody who doesn't just want to downgrade their version.
这在运行我的 node.js 服务器时修复了我的错误,希望这可以帮助那些不想降级他们的版本的人。
(also, if you don't know your db name for some reason, just do a console.log(database) and you'll see it as an object attribute)
(另外,如果您由于某种原因不知道您的数据库名称,只需执行 console.log(database) ,您就会将其视为对象属性)
EDIT (June 2018):
编辑(2018 年 6 月):
According to this, the callback actually returns the connected client of the database, instead of the database itself.
根据此,回调实际上返回数据库的连接的客户端,而不是数据库本身。
Therefore, to get the database instance, we need to use this method, which takes in a dbName. In the documentation it said If not provided, use database name from connection string., as mentioned by @divillysausages in the comments below.
因此,要获取数据库实例,我们需要使用这个方法,它接受一个dbName. 在它说的文档中If not provided, use database name from connection string.,正如@divillysausages 在下面的评论中提到的那样。
In short, we should call database.db().collection('theCollectionIwantToAccess');if the dbName is provided by url, where the databaseis actually clientfor better understanding
总之,database.db().collection('theCollectionIwantToAccess');如果dbName是由url提供的,我们应该调用,database实际上是client为了更好地理解
回答by antikytheraton
The error is in the mongodb library. Try to install version 2.2.33of mongodb. Delete your node_modulesdirectory and add
错误在 mongodb 库中。尝试安装版本2.2.33的mongodb。删除您的node_modules目录并添加
"dependencies": {
"mongodb": "^2.2.33"
}
Then
然后
npm install
and there you are
你在那里
回答by Shashi Kiran
MongoClient.connect(uristring, function (err, database) {
var db=database.db('chatroomApp');
var collections=db.collection('chats');
});
Need to Get the Database first before trying to access the collections.
在尝试访问集合之前需要先获取数据库。
回答by Dilum Darshana
According to the mongo document, we need to change the connection as bellow,
根据mongo文档,我们需要改变连接如下,
The legacy operation
MongoClient.connect('mongodb://localhost:27017/test', (err, db) => {
// Database returned
});
is replaced with
MongoClient.connect('mongodb://localhost:27017/test', (err, client) => {
// Client returned
var db = client.db('test');
});
Don't need to downgrade the mongo version :)
不需要降级mongo版本:)
回答by Naveen Kumar V
Uninstalling existing mongodb package and reinstalling using the following commands resolved the issues for me. :)
卸载现有的 mongodb 包并使用以下命令重新安装为我解决了这些问题。:)
npm uninstall mongodb --save
npm install [email protected] --save
PS:Thanks to @MihirBhende and @yaxartes
PS:感谢@MihirBhende 和@yaxartes
FYI,
供参考,
Prefer non-rc releases from https://github.com/mongodb/node-mongodb-native/releases, if you are new to the field.
如果您是该领域的新手,则更喜欢来自https://github.com/mongodb/node-mongodb-native/releases 的非 rc 版本。
回答by Pulkit Aggarwal
I ran into the same issue. It looks like the mongodb driver module for node was updated since the video was created. I found the code below in the docs which works.
我遇到了同样的问题。自创建视频以来,节点的 mongodb 驱动程序模块似乎已更新。我在文档中找到了下面的代码。
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/<dbName>';
MongoClient.connect(url, (err, db) => {
db.collection('<collection-name>').find({}).toArray(function(err, docs) {
// Print the documents returned
docs.forEach(function(doc) {
console.log(doc);
});
// Close the DB
db.close();
});
});
is replaced with
被替换为
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017'; // remove the db name.
MongoClient.connect(url, (err, client) => {
var db = client.db(dbName);
db.collection('<collection-name>').find({}).toArray(function(err, docs) {
// Print the documents returned
docs.forEach(function(doc) {
console.log(doc);
});
// Close the DB
client.close();
});
});
Here is a linkto the latest docs in case we run into further syntax issues.
这是最新文档的链接,以防我们遇到进一步的语法问题。
回答by Alexandr Shmidt
Thanks a lot to Dilum Darshana! Your advice helped a lot. I just want to add, that, if you use promises it will looks like this:
非常感谢 Dilum Darshana!你的建议很有帮助。我只想补充一点,如果你使用 promises,它看起来像这样:
let db;
MongoClient.connect('mongodb://localhost/collectionName').then(connection => {
db = connection.db('collectionName');
app.listen(3000, () => {
console.log("App started on port 3000");
});
}).catch(error => {
console.log('ERROR:', error);
});
回答by Krish
For the recent version I was using "mongodb": "^3.1.3"Below code solved my issue
对于我使用的最新版本,"mongodb": "^3.1.3"下面的代码解决了我的问题
in server.js
在 server.js
MongoCLient.connect(db.url,(err,client)=>{
var db=client.db('notable123');
if(err){
return console.log(err);
}
require('./server-app/routes')(app,db);
app.listen(port, ()=> {
console.log("we are live on : "+ port);
})
})
and your post code is like
你的邮政编码就像
module.exports = function(app,db) {
app.post('/notes',(req,res)=>{
const note= {text: req.body.body,title:req.body.title};
db.collection('notes').insertOne(note,(err,result)=>{
if(err) {
res.send({"error":"Ann error has occured"});
} else {
res.send(result.ops[0])
}
});
});
};
回答by Yong-bin Jeong
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) => {
...
db -> client
数据库 -> 客户端
module.exports = function(app, client) {
var db = client.db("name");
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
...

