db.collection 不是使用 MongoClient v3.0 时的函数 [英] db.collection is not a function when using MongoClient v3.0
问题描述
我一直在使用 MongoDB 在 nodeJS 上尝试 W3schools 教程.
I have been trying W3schools tutorial on nodeJS with MongoDB.
当我尝试在 nodeJS 环境中实现此示例并使用 AJAX 调用调用该函数时,出现以下错误:
When I try to implement this example in a nodeJS environment and invoke the function with an AJAX call, I got the error below:
TypeError: db.collection is not a function
at c:UsersuserDesktopWeb ProjectWebService.JS:79:14
at args.push (c:Usersuser
ode_modulesmongodblibutils.js:431:72)
at c:Usersuser
ode_modulesmongodblibmongo_client.js:254:5
at connectCallback (c:Usersuser
ode_modulesmongodblibmongo_client.js:933:5)
at c:Usersuser
ode_modulesmongodblibmongo_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) {}
另外,请注意(以防万一)我已经为节点 JS 安装了最新的 MongoDB 包(npm install mongodb),并且 MongoDB 版本是 MongoDB Enterprise 3.4.4,带有 MongoDB Node.js 驱动 v3.0.0-rc0.
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.
推荐答案
我遇到了同样的事情.在 package.json 中,将 mongodb 行更改为mongodb":^2.2.33".您需要通过删除 MongoDB Driver/node_modules 等来卸载 mongodb npm,然后安装 npm 以安装此版本.
I encountered the same thing. In package.json, change mongodb line to "mongodb": "^2.2.33". You will need to uninstall mongodb npm by removing MongoDB Driver/ node_modules or etc , then install npm to install this version.
这为我解决了问题.似乎是一个错误或文档需要更新.
This resolved the issue for me. Seems to be a bug or docs need to be updated.
这篇关于db.collection 不是使用 MongoClient v3.0 时的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!