当使用MongoClientv3.0时,db.Collection不是函数

当使用MongoClientv3.0时,db.Collection不是函数

我一直在努力W3学校教程关于MongoDB的NodeJS。

当我试图在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安装MongoDB),而MongoDB版本是MongoDBEnterprise3.4.4,MongoDBNode.js驱动程序v3.0.0-rc0。


胡子哥哥
浏览 1035回答 3
3回答

qq_花开花谢_0

我也遇到过同样的事情。在Package.json中,将MongoDB行更改为“MongoDB”:“^2.2.33”。您将需要NPM卸载MongoDB,然后再安装NPM安装此版本。这为我解决了这个问题。似乎是一个bug或文档需要更新。

红糖糍粑

对于希望继续使用版本^3.0.1的用户,请注意对如何使用MongoClient.connect()方法。回调不返回db相反它回来了client,其中有一个名为db(dbname)必须调用它才能获得db比如你在找。const MongoClient = require('mongodb').MongoClient;const assert = require('assert'); // Connection URLconst url = 'mongodb://localhost:27017'; // Database Nameconst dbName = 'myproject'; // Use connect method to connect to the serverMongoClient.connect(url, function(err, client) {   assert.equal(null, err);   console.log("Connected successfully to server");   const db = client.db(dbName);   client.close();});
打开App,查看更多内容
随时随地看视频慕课网APP