簡體   English   中英

類型錯誤: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

服務器.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); 
    });

})

數據庫.js

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

索引.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]);
      }
    });
  });
};

所以我投票贊成只降到 mongodb 2.2.33 的答案,因為我試過了並且它有效,但后來我覺得降級以解決問題很奇怪所以我找到了允許你保持版本>=的解決方案3.0。 如果有人發現這個問題並且他們的問題不是像接受的答案那樣傳遞空白參考,請嘗試這個解決方案。

跑的時候..

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

在 mongodb 版本 >= 3.0 中,該database變量實際上是您嘗試使用database.collection('whatever')訪問的對象的父對象。 要訪問正確的對象,您需要引用您的數據庫名稱,對我來說就是這樣做

MongoClient.connect(db.url,(err,database) =>{ 
  const myAwesomeDB = database.db('myDatabaseNameAsAString')
  myAwesomeDB.collection('theCollectionIwantToAccess')
}

這修復了我在運行我的 node.js 服務器時的錯誤,希望這能幫助那些不想降級他們版本的人。

(此外,如果您出於某種原因不知道您的數據庫名稱,只需執行一個 console.log(database) ,您就會將其視為一個對象屬性)


編輯(2018 年 6 月):

據此,回調實際上返回的是數據庫的連接客戶端,而不是數據庫本身。

因此,要獲取數據庫實例,我們需要使用這個方法,它接受一個dbName 在文檔中說If not provided, use database name from connection string. ,正如@divillysausages 在下面的評論中提到的那樣。

簡而言之,我們應該調用database.db().collection('theCollectionIwantToAccess'); 如果dbName是url提供的,這里的database實際上是client ,方便理解

錯誤在 mongodb 庫中。 嘗試安裝2.2.33版的mongodb 刪除您的node_modules目錄並添加

"dependencies": {
   "mongodb": "^2.2.33"
}

然后

npm install

你在那里

MongoClient.connect(uristring, function (err, database) {
      var db=database.db('chatroomApp');
      var collections=db.collection('chats');
});

在嘗試訪問集合之前需要先獲取數據庫。

根據 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');
});

不需要降級 mongo 版本:)

卸載現有的 mongodb 包並使用以下命令重新安裝為我解決了這些問題。 :)

npm uninstall mongodb --save

npm install mongodb@2.2.33 --save

PS:感謝@MihirBhende 和@yaxartes

供參考,

如果您是該領域的新手,請首選來自https://github.com/mongodb/node-mongodb-native/releases的非 rc 版本。

在你的 server.js 中,你正在傳遞空對象,你需要將數據庫作為第二個參數傳遞給你的 routes/index.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); 
    });

});

我遇到了同樣的問題。 自視頻創建以來,節點的 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();
    });

});  

被替換為

 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();
        });

    });  

這是最新文檔的鏈接,以防我們遇到更多語法問題。

對於我使用的最新版本"mongodb": "^3.1.3"下面的代碼解決了我的問題

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);
    })

})

你的郵政編碼就像

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])
            }
        });
    });
};
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) => {
...

數據庫 -> 客戶端

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) => {
...

非常感謝 Dilum Darshana。 你的建議很有幫助,我只想補充一點:如果你使用承諾,它看起來像這樣:

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);
});

在你的 package.json 中。

確保以下版本如下所示:

"nodemon": "^1.12.1"
"mongodb": "^2.2.33"

上面的 nodemon 和 mongodb 版本一起工作沒有任何錯誤。 所以你的 package.json 應該看起來像這樣:

    {
  "name": "myapi",
  "version": "1.0.0",
  "description": "Json Api",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon server.js"
  },
  "author": "Riley Manda",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "mongodb": "^2.2.33"
  },
  "devDependencies": {
    "nodemon": "^1.12.1"
  }
}

降級后不要忘記運行npm install

也有這個問題,我正在學習一個教程,其中演示者將集合用作函數。 它從來沒有為我工作。 我發現演示者使用的是 2.3.4 版的 mongodb npm 模塊。 該模塊現在已進入 3.xx 版。 當我更改 package.json 文件以請求 mogodb npm 模塊的 2.xx 版本時,突然一切正常。

我認為發生的事情是更改了模塊以將集合更改為不同的對象。 不知道如何使用新版本,但如果您指定要使用 2.xx 版本,則舊方法應該有效。 具體來說,我可以確認(來自我的 package.json 文件,“依賴項”部分)“mongodb”:“^2.2.31”有效。

最好的辦法:

$> npm install mongodb@2.2.31 --save
MongoClient.connect(db.url,(err,database) =>{
    if (err) return console.log(err)
    //require('./app/routes')(app,{});
    //try this 
     require('./app/routes')(app,database);
    app.listen(port,() => {
        console.log("We are live on"+port); 
    });
})

在這里您必須將數據庫包含在空的 {} 中。

要么

您也可以嘗試將 mongodb 安裝到最新版本,這將解決問題。

npm install mongodb@2.2.33 --save 

否則 npm install 在節點模塊中添加 "mongodb": "^2.2.33" 的依賴項。

工作代碼使用:

npm version 6.0.1,
Node version 10.1.0
"body-parser": "^1.18.3",
"express": "^4.16.3",
"mongodb": "^3.1.0-beta4"
"nodemon": "^1.17.4"

這是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, { useNewUrlParser: true },  (err, client)=>{
    var db = client.db('notable');
    if (err) return console.log(err)

    require('./app/routes')(app, client);
    app.listen(port,()=>{
        console.log('we are live at '+ port);
    });
})

這是config/db.js代碼:

module.exports = {
    url:"mongodb://127.0.0.1:27017"
}

這是routes/note_routes.js

 var ObjectId = require('mongodb').ObjectID;
 module.exports= function (app, client) {
        var db = client.db('notable');
        //find One
        app.get('/notes/:id', (req, res)=>{
                const id =req.params.id;
                const details ={'_id': new ObjectId(id)}
                db.collection('notes').findOne(details, (err, item)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send(item)
                    }
                });
            });
            //update rout
            app.put('/notes/:id', (req, res)=>{
                const id =req.params.id;
                const details ={'_id': new ObjectId(id)}
                const note ={text: req.body.body, title: req.body.title};
                db.collection('notes').update(details, note, (err, item)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send(item)
                    }
                });
            });

            //delete route
            app.delete('/notes/:id', (req, res)=>{
                const id =req.params.id;
                const details ={'_id': new ObjectId(id)}
                db.collection('notes').remove(details, (err, item)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send("Note "+id+"deleted!")
                    }
                });
            });
            //insert route
            app.post('/notes', (req, res)=>{
                const note ={text: req.body.body, title: req.body.title};
                db.collection('notes').insert(note, (err, results)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send(results.ops[0])
                    }
                });

            });
        };

不要在連接 url 中使用數據庫名稱:

const mongo_url = 'mongodb://localhost:27017'

而是使用以下方法:

MongoClient.connect(mongo_url , { useNewUrlParser: true }, (err, client) => {
        if (err) return console.log(err)
        const  db =  client.db('student')
        const collection = db.collection('test_student');
        console.log(req.body);
        collection.insertOne(req.body,(err,result)=>{
            if(err){
                res.json(err);
            }
            res.json(result);
        });
    });
const MongoClient = require('mongodb').MongoClient;

//connection url

 const url = 'mongodb://localhost:27017/myproject';

 MongoClient.connect(url,{useNewUrlParser: true},(err,client)=> {
  if(err) {
    return console.dir(err)
  }

   console.log('Connected to MongoDB')

  //get the collection
  let db = client.db('myproject');
  db.collection('users').insertOne({
  name: 'Hello World',
  email: 'helloworld@test.com'

  },(err,result)=> {
  if(err) {
      return console.dir(err)
  }
  console.log("Inserted Document");
  console.log(result);

     });
   });

我有簡單的解決方案:

note_routes.js

db.collection('notes').insert(note, (err, result) => {

代替

db.db().collection('notes').insert(note, (err, result) => {

我正在做同樣的教程有同樣的問題。 我剛剛檢查了所有答案並找到了適合我的答案。

MongoClient.connect(db.url, { useUnifiedTopology: true }, (err, client) => {
var database = client.db('test');
if (err) return console.log(err) 
require('./app/routes')(app, database);
app.listen(port, () => { console.log('We are live on ' + port);}); })

將數據庫更改為客戶端並將數據庫定義為 client.db('test')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM