Javascript TypeError:db.collection不是具有用户密码限制的函数

Javascript TypeError:db.collection不是具有用户密码限制的函数,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我有一个大学项目,我可以通过ssh连接到一个服务器,该服务器有一个固定数据库/用户名/密码的mongodb。我导入了一个集合,现在想用nodejs读取它进行测试。在使用node server.js启动它之后,它将“正确连接到服务器”返回到控制台,但随后我得到一个TypeError:db.collection不是一个函数 怎么了?谢谢 var MongoClient = require('mongodb').MongoClient; const user = encodeURIComponent

我有一个大学项目,我可以通过ssh连接到一个服务器,该服务器有一个固定数据库/用户名/密码的mongodb。我导入了一个集合,现在想用nodejs读取它进行测试。在使用node server.js启动它之后,它将“正确连接到服务器”返回到控制台,但随后我得到一个TypeError:db.collection不是一个函数

怎么了?谢谢

var MongoClient = require('mongodb').MongoClient;

const user = encodeURIComponent('x');
const password = encodeURIComponent('y');
const authMechanism = 'DEFAULT';

// Connection URL
const url = `mongodb://${user}:${password}@localhost:27017/database?authMechanism=${authMechanism}`;


MongoClient.connect(url, function(err, db) {

    console.log("Connected correctly to server");//works

    var cursor = db.collection('locations').find();//throws error

    cursor.each(function(err, doc) {

        console.log(doc);

    });
}); 
试着这样做:

var MongoClient = require('mongodb').MongoClient;

const user = encodeURIComponent('x');
const password = encodeURIComponent('y');
const authMechanism = 'DEFAULT';

// Connection URL
const url = `mongodb://${user}:${password}@localhost:27017/database?authMechanism=${authMechanism}`;


MongoClient.connect(url, function(err, db) {
    if(err){
        console.log("Connection failed");
    }
    else{

        console.log("Connected correctly to server");

        var cursor = db.collection('locations');//same error

        cursor.find({}).toArray(function(err,docs){
            if(err){
                console.log("did'nt find any!")
            }
            else{
                console.log(docs)
            }
        });
    }
});

毕竟,它起作用了:

var MongoClient = require('mongodb').MongoClient;

const user = encodeURIComponent('x');
const password = encodeURIComponent('y');
const authMechanism = 'DEFAULT';

// Connection URL with and without authentication
const url = `mongodb://${user}:${password}@localhost:27017/database?authMechanism=${authMechanism}`;
//const url = `mongodb://localhost:27017/`;

MongoClient.connect(url, (err, db) => {
    if(err) throw err;

    console.log("connect works");

    let database = db.db('database');

    database.collection('users').find().toArray((err, results) => {
        if(err) throw err;
        results.forEach((value)=>{
            console.log(value);
        });
    })
});

您需要先检查错误。在您的
console.log()
之前,您应该检查
err
是否不为空。我如何才能做到这一点?如果(!err){console.log(…);}或者{console.log(err);}?不要在这里发布,请尝试代码:)两次console.log(“没有找到任何!”)。第二个else2nd中应该包含的内容将显示它从数据库中得到的响应我修复了您的代码,但仍然得到相同的类型错误:db.collection不是一个函数看到了吗