TypeError: db.collection is not a function

后端 未结 18 2453
青春惊慌失措
青春惊慌失措 2020-11-27 03:09

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 o

相关标签:
18条回答
  • 2020-11-27 03:33

    For the recent version I was using "mongodb": "^3.1.3" Below code solved my issue

    in 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])
                }
            });
        });
    };
    
    0 讨论(0)
  • 2020-11-27 03:33

    I am doing the same tutorial having the same issue. I just checked all the answers and found the one for me.

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

    changed database to client and define the database as client.db('test')

    0 讨论(0)
  • 2020-11-27 03:36

    According to the mongo document, we need to change the connection as bellow,

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

    0 讨论(0)
  • 2020-11-27 03:36

    Working code using:

    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"
    

    Here is server.js code:

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

    Here is config/db.js code:

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

    Here is 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])
                        }
                    });
    
                });
            };
    
    0 讨论(0)
  • 2020-11-27 03:38

    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

    0 讨论(0)
  • 2020-11-27 03:38

    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:

    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);
    });
    
    0 讨论(0)
提交回复
热议问题