TypeError: db.collection is not a function

后端 未结 18 2460
青春惊慌失措
青春惊慌失措 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条回答
  •  -上瘾入骨i
    2020-11-27 03:21

    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.

    var MongoClient = require('mongodb').MongoClient;
    
    var url = 'mongodb://localhost:27017/';
    MongoClient.connect(url, (err, db) => {
       db.collection('').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('').find({}).toArray(function(err, docs) {
    
            // Print the documents returned
            docs.forEach(function(doc) {
                console.log(doc);
            });
    
            // Close the DB
            client.close();
            });
    
        });  
    

    Here is a link to the latest docs in case we run into further syntax issues.

提交回复
热议问题