【发布时间】:2015-08-08 19:52:04
【问题描述】:
我找到了一些在 shell 中列出集合的答案,但我找到的所有在 nodejs 脚本中列出集合的答案似乎都已被弃用,collectionNames 和 moongose.connection.db return 之类的答案没有方法。
【问题讨论】:
标签: node.js mongodb collections
我找到了一些在 shell 中列出集合的答案,但我找到的所有在 nodejs 脚本中列出集合的答案似乎都已被弃用,collectionNames 和 moongose.connection.db return 之类的答案没有方法。
【问题讨论】:
标签: node.js mongodb collections
在 2.0 版本的 node.js 的 MongoDB 驱动程序中,您可以使用listCollections 获取包含所有集合信息的游标。然后您可以在光标上调用toArray 来检索信息。
db.listCollections().toArray(function(err, collInfos) {
// collInfos is an array of collection info objects that look like:
// { name: 'test', options: {} }
});
【讨论】:
这是一个完整的示例,说明如何使用 3.4 版本的 Mongo 节点驱动程序
const MongoClient = require("mongodb").MongoClient;
// Connection url
var url = 'mongodb://localhost:27017/test';
const client = new MongoClient(url, { useUnifiedTopology: true }); // { useUnifiedTopology: true } removes connection warnings;
const dbName = "test";
client
.connect()
.then(
client =>
client
.db(dbName)
.listCollections()
.toArray() // Returns a promise that will resolve to the list of the collections
)
.then(cols => console.log("Collections", cols))
.finally(() => client.close());
【讨论】:
如果您有权访问async/await,则在迭代器上承诺toArray 并且不使用回调会更简洁。
static toArray(iterator) {
return new Promise((resolve, reject) => {
iterator.toArray((err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
const myArray = await toArray(db.listCollections());
【讨论】:
const collections = Object.keys(mongoose.connection.collections);
这会为您提供您的收藏的 JSON 文档。
【讨论】:
var resource=[];
var ob=db.getSiblingDB('working_db');
ob.getCollectionNames().forEach(function(doc){
var regex = /^word|word1|word2|word3/i;
var found = doc.match(regex);
if(found){
printjson(doc)
resource.push({ resource: { db: "working_db", collection: doc }, actions: [ "insert","find","remove","update"] })
}
});
正则表达式用于获取我们需要列出的集合前缀名称中的特定特定单词,如果您不需要,则将其删除。 这对于从大量集合中授予集合特定权限非常有用。
use admin,
db.createRole(
{
role: "ROLE_NAME",
privileges: resource,
roles: [
{
role: "clusterMonitor",
db: "admin"
}
]
}
)
【讨论】: