如何使用 Node.js 检查 MongoDB 中是否存在集合?

Ral*_*thy 5 mongoose mongodb node.js express pug

基本上,我想根据集合是否存在来隐藏div。有谁知道最简单的方法吗?我在 Jade 中使用 Mongoose 和 Express.js。

Joh*_*one 3

如果你想通过node.js本机api直接访问mongodb,你可以使用db.collectionNames():

\n\n
\n

列出现有集合

\n\n

列出姓名

\n\n

可以使用 collectionNames 列出集合

\n\n

db.collectionNames(回调);

\n\n

回调获取两个参数 - 一个错误对象(如果发生错误)和一个字符串形式的集合名称数组。

\n\n

集合名称还包括数据库名称,因此数据库博客中名为 posts 的集合将列为 blog.posts。

\n\n

此外,在不确切知道您在做什么的情况下,不应更改\xe2\x80\x99s 系统集合,这些集合可以用系统前缀\n 进行标识。例如 posts.system.indexes。

\n\n

例子:

\n
\n\n
var MongoClient = require(\'mongodb\').MongoClient   , format = require(\'util\').format;\n\nMongoClient.connect(\'mongodb://127.0.0.1:27017/test\', function(err, db) {\n\n  if(err) throw err;   \n  db.collectionNames(function(err, collections){\n       console.log(collections);   \n  }); \n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

http://mongodb.github.io/node-mongodb-native/markdown-docs/collections.html

\n

  • 自此迁移以来,该方法不再存在:http://mongodb.github.io/node-mongodb-native/2.0/meta/changes-from-1.0/ (2认同)