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

时间:2019-01-13 15:40:17

标签: javascript node.js mongodb

我有一个大学项目,可以在其中SSH服务器到具有固定数据库/用户名/密码的mongodb的服务器。我导入了一个集合,现在想用nodejs读出它进行测试。用节点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);

    });
}); 

2 个答案:

答案 0 :(得分:0)

尝试这种方式:

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

答案 1 :(得分:0)

让它一切正常:

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