node.js - db.createCollection 不是函数

标签 node.js mongodb docker

我正在尝试创建一个 mongo 实例,但是我无法从 mongodb nodejs 驱动程序访问任何辅助方法。

我的 mongo 实例在 docker 中运行,并且端口已向我的本地开放。

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 复制...

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 对象上公开任何方法。

有什么想法吗?

最佳答案

根据changelog对于 Mongodb 3.0,您现在会得到一个包含数据库对象的客户端对象:

所以你需要 db 对象指向你想使用的数据库,在你的例子中是 mydb。试试这个:

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

关于node.js - db.createCollection 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47658775/

相关文章:

javascript - 如何进一步拆分 JavaScript 对象中的字符串?

node.js - 使用 mocha/superagent 测试本地 https 服务器

javascript - 如何模拟回调函数以测试其位于另一个函数的参数内

mongodb - Mongorestore 到不同的数据库

javascript - 当我向我的网站注册新用户时,出现此错误“secretOrPrivateKey 必须具有值”! Node.js

node.js - Docker 容器和 Node.js 集群

node.js - Mongoose 模式方法返回不是一个函数

javascript - Mongodb Nodejs 正则表达式查询

docker - 复制文件时 Jenkins 权限被拒绝

docker - 如何将 Docker 容器日志大小限制为预定义值