db.createCollection不是函数 [英] db.createCollection is not a function

查看:100
本文介绍了db.createCollection不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆