簡體   English   中英

db.collection 不是使用 MongoClient v3.0 時的函數

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

我一直在使用 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)

請在下面找到我實現的代碼:

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

請注意,只要執行命中就會發生錯誤:

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

另外,請注意(以防萬一)我已經為節點 JS 安裝了最新的 MongoDB 包( npm install mongodb ),並且 MongoDB 版本是 MongoDB Enterprise 3.4.4,帶有 MongoDB Node.js 驅動程序 v3.0.0-rc0。

對於使用 MongoDB 原生 NodeJS 驅動程序 3.0 版的用戶:

(這適用於擁有 "mongodb": "^3.0.0-rc0" 或 package.json 中更高版本的人,希望繼續使用最新版本。)

MongoDB 本機 NodeJS 驅動程序的2.x 版中,您將獲得數據庫對象作為連接回調的參數:

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

根據 3.0 的變更日志,您現在得到一個包含數據庫對象的客戶端對象:

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

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

我遇到了同樣的事情。 在 package.json 中,將 mongodb 行更改為 "mongodb": "^2.2.33"。 您需要通過刪除 MongoDB Driver/ node_modules 等來卸載 mongodb npm,然后安裝 npm 以安裝此版本。

這為我解決了這個問題。 似乎是一個錯誤或文檔需要更新。

對於那些想要繼續使用 ^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();
});
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);
        });
    })
})

您的代碼的唯一問題是您正在訪問持有數據庫處理程序的對象。 您必須直接訪問數據庫(請參閱上面的數據庫變量)。 此代碼將在數組中返回您的數據庫,然后循環遍歷它並記錄數據庫中每個人的名稱。

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

我做了一些實驗,看看是否可以將數據庫名稱保留為 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));

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

如果您願意處理棄用警告,則不需要 'useNewUrlParser' 選項。 但在版本 4 出現之前,此時使用它是明智的,其中新驅動程序可能是默認驅動程序,您將不再需要該選項。

我通過運行這些代碼輕松解決了它:

 npm uninstall mongodb --save

 npm install mongodb@2.2.33 --save

快樂編碼!

如果有人仍在嘗試如何解決此錯誤,我已經這樣做了,如下所示。

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

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

它曾經適用於舊版本的MongoDb 客戶端 ~ 2.2.33

選項 1:因此您可以使用舊版本

npm uninstall mongodb --save

npm install mongodb@2.2.33 --save

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

MongoDB 查詢將游標返回到存儲在內存中的數組。 要訪問該數組的結果,您必須在查詢結束時調用.toArray()

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

遲到的答案,但也許將來有人會需要它

我們可以創建異步函數,它將返回我們的集合和數據庫實例

const dBInstances = async () => {
  const collection = await db
    .then((client) => {
      const db = client.db();
      const collection = db.collection("AGGREGATION");
      return { collection: collection, db: db };
    })
    .catch((err) => {
      console.log(`Data base instances error ${err}`);
    });

  return collection;
};

在我們可以通過這種方式使用執行結果 dBInstances() 之后,我在下面的示例中使用了 JS 解構

const test = async (req, res) => {
  const { collection, db } = await dBInstances();
  console.log(collection);
  console.log(db);
};

現在我們可以分開訪問我們的數據庫和集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM