'process.nextTick(function(){throw err;})' - 未定义不是函数(mongodb/mongoose)

Fan*_*ane 13 mongoose mongodb node.js socket.io

我正在尝试使用nodejs和socket.io 连接到我的mongodb.我能够连接到数据库,因为我在我的控制台中接受'连接'但在nodejs端,我 - 确实 - 得到

通过mongoose连接到mongodb:// localhost:27017

它立即失败了

process.nextTick(function(){throw err;})^ TypeError:undefined不是showCollections中的函数**

这里是showCollections:

var showCollections = function(db, callback) { 
    mongoose.connection.db.collectionNames(function(error, names) {
    if (error) {
      throw new Error(error);
    } else {
        console.log("=>Listening mongo collections:");
      names.map(function(cname) {
        mongoose.connection.db.dropCollection(cname.name);
        console.log("--»"+cname.name);
      });
    }
  });

}
Run Code Online (Sandbox Code Playgroud)

这是我的数据库文件夹的内容:

_tmp (empty folder)
local.0
local.ns
mongod.lock
Run Code Online (Sandbox Code Playgroud)

我通过键入mongod --dbpath文件夹运行mongodb ,它成功'等待端口27017上的连接'.

另外,来自package.json(npm)的node_modules

"dependencies": {
    "express": "^4.9.6",
    "socket.io": "latest",
    "mongodb": "~2.0",
    "mongoose": "*"
  }
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助...

堆栈跟踪:

> TypeError: undefined is not a function
>     at showCollections (/usr/share/nginx/www/index.js:77:25)
>     at NativeConnection.callback (/usr/share/nginx/www/index.js:46:3)
>     at NativeConnection.g (events.js:199:16)
>     at NativeConnection.emit (events.js:104:17)
>     at open (/usr/share/nginx/www/node_modules/mongoose/lib/connection.js:485:10)
>     at NativeConnection.Connection.onOpen (/usr/share/nginx/www/node_modules/mongoose/lib/connection.js:494:5)
>     at /usr/share/nginx/www/node_modules/mongoose/lib/connection.js:453:10
>     at /usr/share/nginx/www/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:59:5
>     at /usr/share/nginx/www/node_modules/mongoose/node_modules/mongodb/lib/db.js:200:5
>     at connectHandler (/usr/share/nginx/www/node_modules/mongoose/node_modules/mongodb/lib/server.js:272:7)
Run Code Online (Sandbox Code Playgroud)

编辑:

在尝试运行nodejs实例时,我也遇到了这些问题:

{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
Run Code Online (Sandbox Code Playgroud)

我尝试修理它们,因为这里的其他问题会说明但是没有任何作用......

小智 34

从提供的信息,看起来你正在使用mongodb 2.0驱动程序.db.collectionNames方法已被删除.查看本页的"Db对象"部分 - https://github.com/mongodb/node-mongodb-native/blob/0642f18fd85037522acf2e7560148a8bc5429a8a/docs/content/tutorials/changes-from-1.0.md#L38

他们用listCollections替换了它.你应该得到同样的效果:

mongoose.connection.db.listCollections().toArray(function(err, names) {
    if (err) {
        console.log(err);
    }
    else {
        names.forEach(function(e,i,a) {
            mongoose.connection.db.dropCollection(e.name);
            console.log("--->>", e.name);
        });
    }
});
Run Code Online (Sandbox Code Playgroud)