db.createCollection不是函数 [英] db.createCollection is not a function
问题描述
我正在尝试创建mongo实例,但是无法从mongodb nodejs驱动程序访问任何帮助程序方法.
I am attempting to create a mongo instance however I am unable to access any of the helper methods from the mongodb nodejs driver.
我的mongo实例正在docker中运行,并且端口已向我的本地开放.
My mongo instance is running within docker and the ports have been opened up to my local.
TypeError: db.createCollection is not a function
at /var/www/html/beacon/index.js:6:8
at args.push (/var/www/html/beacon/node_modules/mongodb/lib/utils.js:431:72)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:254:5
at connectCallback (/var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:933:5)
at /var/www/html/beacon/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)
从w3schools复制了...
Copied from w3schools...
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
运行不会返回任何错误,并且db对象上没有公开任何方法.
No error is returned through the run, and no methods are exposed on the db object.
有什么想法吗?
推荐答案
According to the changelog for Mongodb 3.0 you now get a client object containing the database object instead:
因此,您需要db
对象,该对象指向要使用的数据库,在本例中为mydb.试试这个:
So you need the db
object that points to the database you want to use, in your case mydb. Try this:
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) { //here db is the client obj
if (err) throw err;
var dbase = db.db("mydb"); //here
dbase.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close(); //close method has also been moved to client obj
});
});
这篇关于db.createCollection不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!