使用MongoClient v3.0时,db.collection不是函数

Eli*_*mar 117 mongodb node.js

我一直在使用MongoDB在nodeJS上尝试W3schools教程.

当我尝试在nodeJS环境中实现此示例并使用AJAX调用调用该函数时,我收到以下错误:

TypeError: db.collection is not a function
    at c:\Users\user\Desktop\Web Project\WebService.JS:79:14
    at args.push (c:\Users\user\node_modules\mongodb\lib\utils.js:431:72)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:254:5
    at connectCallback (c:\Users\user\node_modules\mongodb\lib\mongo_client.js:933:5)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:794:11
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
Run Code Online (Sandbox Code Playgroud)

请在下面找到我实现的代码:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mytestingdb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  db.collection("customers").findOne({}, function(err, result) {
    if (err) throw err;
    console.log(result.name);
    db.close();
  });
});
Run Code Online (Sandbox Code Playgroud)

请注意,只要执行命中,就会发生错误:

db.collection("customers").findOne({}, function(err, result) {}
Run Code Online (Sandbox Code Playgroud)

另外,请注意(如果重要的话)我已经为节点JS安装了最新的MongoDB软件包(npm install mongodb),而MongoDB版本是MongoDB Enterprise 3.4.4,使用MongoDB Node.js驱动程序v3.0.0-rc0.

Mik*_*kaS 426

对于MongoDB本机NodeJS驱动程序3.0版本的人员:

(这适用于那些想要继续使用最新版本的"mongodb":"^ 3.0.0-rc0"或package.json中的更新版本.)

MongoDB本机NodeJS驱动程序的 2.x版中,您将获取数据库对象作为connect回调的参数:

MongoClient.connect('mongodb://localhost:27017/mytestingdb', (err, db) => {
  // Database returned
});
Run Code Online (Sandbox Code Playgroud)

根据3.0 的changelog,您现在获得一个包含数据库对象的客户端对象:

MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  // Client returned
  var db = client.db('mytestingdb');
});
Run Code Online (Sandbox Code Playgroud)

close()方法也已移至客户端.因此,问题中的代码可以转换为:

MongoClient.connect('mongodb://localhost', function (err, client) {
  if (err) throw err;

  var db = client.db('mytestingdb');

  db.collection('customers').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
    client.close();
  });
}); 
Run Code Online (Sandbox Code Playgroud)

  • @ozgrozer听起来像是在为每个请求连接数据库.这被认为是一个坏主意.你可以阅读[这里](/sf/answers/1012532531/).如果您只连接一次,则每个应用程序只创建一个新行. (4认同)

Ayo*_*yoO 72

我遇到了同样的事情.在package.json中,将mongodb行更改为"mongodb":"^ 2.2.33".你需要npm卸载mongodb; 然后npm install安装此版本.

这解决了我的问题.似乎是一个bug或文档需要更新.

  • 降级到早期版本并不是一个真正的解决方案,只是意味着你没有费心去研究造成这种情况的API变化 (50认同)
  • 检查MikaS的回答 (14认同)
  • @JohnCulviner - 这是一个时间问题; 不是懒惰问题.在发布新更新的过程中发生此问题.我(和原始海报)显然没有意识到这一点.那时,文档还没有更新.不久后他们就更新了.任何想要解决此问题的人都应该遵循MikaS的评论并查看更新的文档.我在文档更新后也做了同样的事情并且能够继续升级版本. (3认同)
  • 根本没有帮助.为什么它被标记为正确的答案? (3认同)

ra9*_*a9r 29

对于那些想继续使用版本^ 3.0.1的人,请注意对MongoClient.connect()方法的使用方式的更改.回调不返回db而是返回client,对此有一个函数调用db(dbname),你必须调用它来获取db你正在寻找的实例.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});
Run Code Online (Sandbox Code Playgroud)

  • 此答案更新并适用于驱动程序的版本 3。谢谢 (2认同)

Dre*_*son 26

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

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

    database.collection('name').find()
    .toArray((err, results) => {
        if(err) throw err;

        results.forEach((value)=>{
            console.log(value.name);
        });
    })
})
Run Code Online (Sandbox Code Playgroud)

您的代码唯一的问题是您正在访问持有数据库的对象.您必须直接访问数据库(请参阅上面的数据库变量).此代码将在数组中返回您的数据库,然后循环遍历它并记录数据库中每个人的名称.


aga*_*ian 12

对@MikkaS的小猪支持回答Mongo Client v3.x,我只需要async/await格式,看起来略有修改如下:

const myFunc = async () => {

     // Prepping here...


    // Connect
    let client = await MongoClient.connect('mongodb://localhost');
    let db = await client.db();

    // Run the query
    let cursor = await db.collection('customers').find({});

    // Do whatever you want on the result.
}
Run Code Online (Sandbox Code Playgroud)


pwi*_*cox 11

我做了一些实验,看看是否可以将数据库名称保留为 url 的一部分。我更喜欢 promise 语法,但它仍然适用于回调语法。注意下面调用 client.db() 时不传递任何参数。

MongoClient.connect(
    'mongodb://localhost:27017/mytestingdb', 
    { useNewUrlParser: true}
)
.then(client => {

    // The database name is part of the url.  client.db() seems 
    // to know that and works even without a parameter that 
    // relays the db name.
    let db = client.db(); 

    console.log('the current database is: ' + db.s.databaseName);
    // client.close() if you want to

})
.catch(err => console.log(err));
Run Code Online (Sandbox Code Playgroud)

我的 package.json 列出了 monbodb ^3.2.5。

如果您愿意处理弃用警告,则不需要 'useNewUrlParser' 选项。但在版本 4 出现之前,此时使用它是明智的,其中新驱动程序可能是默认驱动程序,您将不再需要该选项。


Rus*_*sty 7

它曾经与旧版本的MongoDb 客户端一起使用~ 2.2.33

选项 1:因此您可以使用旧版本

npm uninstall mongodb --save

npm install mongodb@2.2.33 --save
Run Code Online (Sandbox Code Playgroud)

选项2:继续使用较新的版本(3.0及以上)并稍微修改代码。

let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client){
  if(err) throw err;
  let db = client.db('myTestingDb');
  db.collection('customers').find().toArray(function(err, result){
    if(err) throw err;
    console.log(result);
    client.close();
    });
 });
Run Code Online (Sandbox Code Playgroud)


Sau*_*ngh 5

我通过运行这些代码轻松解决了它:

 npm uninstall mongodb --save

 npm install mongodb@2.2.33 --save
Run Code Online (Sandbox Code Playgroud)

快乐的编码!


Mah*_*a B 5

如果有人仍在尝试如何解决此错误,我已经这样做了,如下所示。

const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'mytestingdb';

const retrieveCustomers = (db, callback)=>{
    // Get the customers collection
    const collection = db.collection('customers');
    // Find some customers
    collection.find({}).toArray((err, customers) =>{
        if(err) throw err;
      console.log("Found the following records");
      console.log(customers)
      callback(customers);
    });
}

const retrieveCustomer = (db, callback)=>{
    // Get the customers collection
    const collection = db.collection('customers');
    // Find some customers
    collection.find({'name': 'mahendra'}).toArray((err, customers) =>{
        if(err) throw err;
      console.log("Found the following records");
      console.log(customers)
      callback(customers);
    });
}

const insertCustomers = (db, callback)=> {
    // Get the customers collection
    const collection = db.collection('customers');
    const dataArray = [{name : 'mahendra'}, {name :'divit'}, {name : 'aryan'} ];
    // Insert some customers
    collection.insertMany(dataArray, (err, result)=> {
        if(err) throw err;
        console.log("Inserted 3 customers into the collection");
        callback(result);
    });
}

// Use connect method to connect to the server
MongoClient.connect(url,{ useUnifiedTopology: true }, (err, client) => {
  console.log("Connected successfully to server");
  const db = client.db(dbName);
  insertCustomers(db, ()=> {
    retrieveCustomers(db, ()=> {
        retrieveCustomer(db, ()=> {
            client.close();
        });
    });
  });
});
Run Code Online (Sandbox Code Playgroud)