【问题标题】:How to check if collection exists in MongoDB with Node.js? [duplicate]如何使用 Node.js 检查 MongoDB 中是否存在集合? [复制]
【发布时间】:2014-06-30 01:32:37
【问题描述】:

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

【问题讨论】:

标签: node.js mongodb express mongoose pug


【解决方案1】:

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

列出现有的集合

列表名称

集合可以用 collectionNames 列出

db.collectionNames(回调);

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

集合名称也包括数据库名称,所以一个集合名为 数据库博客中的帖子将被列为 blog.posts。

此外,还有一些不应更改的系统集合 在不知道你在做什么的情况下,这些 sollections 可以是 用系统前缀标识。例如posts.system.indexes。

例子:

var MongoClient = require('mongodb').MongoClient   , format = require('util').format;

MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {

  if(err) throw err;   
  db.collectionNames(function(err, collections){
       console.log(collections);   
  }); 
});

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

【讨论】:

【解决方案2】:

你可以使用

 db.system.namespaces.find( { name: dbName +'.' + collectionName } );

它包含集合和索引的条目,对于现有集合,它应该返回如下内容:

{ "name" : "temp333.categories" }

要从 mongoose 中执行此操作,您可以定义 system.namespaces 模型和查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 2012-11-06
    • 2015-11-01
    • 2021-09-15
    • 2020-08-11
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多