node.js db.collection 不是使用 MongoClient v3.0 时的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47662220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:36:51  来源:igfitidea点击:

db.collection is not a function when using MongoClient v3.0

node.jsmongodb

提问by Elie Asmar

I have been trying W3schools tutorialon nodeJS with MongoDB.

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

When I try to implement this example in a nodeJS environment and invoke the function with an AJAX call, I got the error below:

当我尝试在 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)

Please find below my implemented code:

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

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

Note that the error occurs whenever the execution hits:

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

db.collection("customers").findOne({}, function(err, result) {}

Also, note (in case it matters) that I have installed the latest MongoDB package for node JS (npm install mongodb), and the MongoDB version is MongoDB Enterprise 3.4.4, with MongoDB Node.js driver v3.0.0-rc0.

另外,请注意(以防万一)我已经为节点 JS 安装了最新的 MongoDB 包(npm install mongodb),并且 MongoDB 版本是 MongoDB Enterprise 3.4.4,带有 MongoDB Node.js 驱动程序 v3.0.0-rc0。

采纳答案by AyoO

I encountered the same thing. In package.json, change mongodb line to "mongodb": "^2.2.33". You will need to npm uninstall mongodb; then npm install to install this version.

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

This resolved the issue for me. Seems to be a bug or docs need to be updated.

这为我解决了这个问题。似乎是一个错误或文档需要更新。

回答by Mika Sundland

For people on version 3.0 of the MongoDB native NodeJS driver:

对于使用 MongoDB 原生 NodeJS 驱动程序 3.0 版的用户:

(This is applicable to people with "mongodb": "^3.0.0-rc0", or a later version in package.json, that want to keep using the latest version.)

(这适用于拥有 "mongodb": "^3.0.0-rc0" 或 package.json 中更高版本的人,希望继续使用最新版本。)

In version 2.x of the MongoDB native NodeJS driveryou would get the database object as an argument to the connect callback:

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

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

According to the changelogfor 3.0 you now get a client object containing the database object instead:

根据3.0的变更日志,您现在得到一个包含数据库对象的客户端对象:

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

The close()method has also been moved to the client. The code in the question can therefore be translated to:

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

回答by ra9r

For those that want to continue using version ^3.0.1 be aware of the changes to how you use the MongoClient.connect()method. The callback doesn't return dbinstead it returns client, against which there is a function called db(dbname)that you must invoke to get the dbinstance you are looking for.

对于那些想要继续使用 ^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();
});

回答by Dre Hymanson

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

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

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

        results.forEach((value)=>{
            console.log(value.name);
        });
    })
})

The only problem with your code is that you are accessing the object that's holding the database handler. You must access the database directly (see database variable above). This code will return your database in an array and then it loops through it and logs the name for everyone in the database.

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

回答by agarcian

Piggy backing on @MikkaS answer for Mongo Client v3.x, I just needed the async / await format, which looks slightly modified as this:

支持 @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.
}

回答by pwilcox

I did a little experimenting to see if I could keep the database name as part of the url. I prefer the promise syntax but it should still work for the callback syntax. Notice below that client.db() is called without passing any parameters.

我做了一些实验,看看是否可以将数据库名称保留为 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));

My package.json lists monbodb ^3.2.5.

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

The 'useNewUrlParser' option is not required if you're willing to deal with a deprecation warning. But it is wise to use at this point until version 4 comes out where presumably the new driver will be the default and you won't need the option anymore.

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

回答by Saurabh Singh

I solved it easily via running these codes:

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

 npm uninstall mongodb --save

 npm install [email protected] --save

Happy Coding!

快乐编码!

回答by Gianluca Mazzeo

I have MongoDB shell version v3.6.4, below code use mongoclient, It's good for me:

我有 MongoDB shell 版本 v3.6.4,下面的代码使用 mongoclient,这对我有好处:

var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var url = 'mongodb://localhost:27017/video';
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, client) 
{
assert.equal(null, err);
console.log("Successfully connected to server");
var db = client.db('video');
// Find some documents in our collection
db.collection('movies').find({}).toArray(function(err, docs) {
// Print the documents returned
docs.forEach(function(doc) {
console.log(doc.title);
});
// Close the DB
client.close();
});
// Declare success
console.log("Called find()");
 });

回答by pmpc2

MongoDB queries return a cursor to an array stored in memory. To access that array's result you must call .toArray()at the end of the query.

MongoDB 查询将游标返回到存储在内存中的数组。要访问该数组的结果,您必须.toArray()在查询结束时调用。

  db.collection("customers").find({}).toArray() 

回答by Mahendra Bagul

If someone is still trying how to resolve this error, I have done this like below.

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

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