Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

node.js - TypeError: db.collection is not a function

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:[email protected]:47510/testing"
};

index.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]);
      }
    });
  });
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

When you run..

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

In mongodb version >= 3.0, That database variable 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

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.

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


EDIT (June 2018):

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.

In short, we should call database.db().collection('theCollectionIwantToAccess'); if the dbName is provided by url, where the database is actually client for better understanding


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...