Mic*_*sov 9 javascript mongodb node.js node-mongodb-native
如何从nodeJS的mongodb本机驱动程序中获取没有数据库名称的集合名称?
db.collectionNames(function(err, collections) {
if (err) {
log.error(err);
} else {
log.info(collections);
}
});
Run Code Online (Sandbox Code Playgroud)
此代码返回如下内容:
databaseName.collection1,databaseName.collection2,databaseName.collection3
但我想得到名字: collection1, collection2, collection3
dsh*_*iro 13
使用MongoDB 2.0.0及更高版本的驱动程序,您需要使用listCollections(),如同
db.listCollections().toArray(function(err, collections){
//collections = [{"name": "coll1"}, {"name": "coll2"}]
});
Run Code Online (Sandbox Code Playgroud)
响应的确切结构是一个子文档,其中“name”键位于数组中:
[
{ name: 'test.cursors' },
{ name: 'test.episodes' },
{ name: 'test.zips' },
{ name: 'test.scripts' }
]
Run Code Online (Sandbox Code Playgroud)
所以只需map与正则表达式一起使用replace:
db.collectionNames(function(err, collections) {
console.log(
collections.map(function(x) {
return x.name.replace(/^([^.]*)./,"");
})
);
});
Run Code Online (Sandbox Code Playgroud)
这将删除第一个.数据库前缀之前的所有内容。以防万一您实际上有包含 a 的集合名称.。
| 归档时间: |
|
| 查看次数: |
6177 次 |
| 最近记录: |