我需要判断某个数据库上是否存在一个集合,如果不存在,就创建它.我知道这一点

db.createCollection(collName, {strict:true}, function(error, collection))

在创建集合collName之前判断集合collName是否存在,并设置error对象.但我需要一个独立的函数来判断.

推荐答案

In MongoDB 3.0 and later, you have to run a command to list all collections in a database:

use test;
db.runCommand( { listCollections: 1 } );

尽管在使用默认存储引擎(MMAPv1)时,查询system.namespaces仍能工作,但不能保证它适用于其他引擎,如WiredTiger.

Before MongoDB 3.0 you need to do the following:

您可以查询system.namespaces个集合:

use test;
db.system.namespace.find( { name: 'test.' + collName } );

比如:

db.system.namespaces.find( { name: 'test.testCollection' } );

返回:

{ "name" : "test.testCollection", "options" : { "flags" : 1 } }

当然,也没什么.

See also: 100

Node.js相关问答推荐

如何使用Node.js、Express和Mongoose创建多个API

为什么在导出的函数中调用node-sqlite3中的数据库方法时不起作用?

获取驱动器文件夹的直接子文件夹时出现问题

如何使用多个参数完成

React原生Nodejs兼容性问题

验证器功能在mongoose 中不起作用

mongodb首先自连接,然后根据某些条件与另一个表连接

FHIR 服务器:尽管 JSON 格式正确,但在 POST 请求中接收未定义请求正文

Cypress.io - 如何等待返回调用属性的方法的结果?

将 null 推入管道后,node.js 可写完成未发出

Google App Engine 突然不允许我部署我的 node.js 应用程序

TypeError:在使用 Jest、Supertest、Express、Typescript 进行测试时无法读取未定义的属性(读取listen)

为什么后端开发需要单独的服务器?

无法使用 node 预签名 url 从 React 将图像文件上传到 s3

等到文件上传完成的有效方法(mongoose )

Node.JS 中的基本 HTTP 身份验证?

使用 node.js 循环 JSON

如何从 find 方法返回 Mongoose 结果?

`return function *(){...}` 是什么意思?

Mongoose - 验证邮箱语法