Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  166] [ 5]  / answers: 1 / hits: 6965  / 10 Years ago, sat, may 17, 2014, 12:00:00

How can I get collection names without database name from mongodb native driver for nodeJS?



db.collectionNames(function(err, collections) {
if (err) {
log.error(err);
} else {
log.info(collections);
}
});


This code returns something like this:




databaseName.collection1, databaseName.collection2, databaseName.collection3




But i want to get names: collection1, collection2, collection3


More From » node.js

 Answers
3

The exact structure of the response is a sub-document with the name key in an array:





[
{ name: 'test.cursors' },
{ name: 'test.episodes' },
{ name: 'test.zips' },
{ name: 'test.scripts' }
]


So just use map with a regex replace:



db.collectionNames(function(err, collections) {

console.log(
collections.map(function(x) {
return x.name.replace(/^([^.]*)./,);
})
);

});


And that will strip out everything up to the first . which is the database prefix. Just in case you actually have collection names with a . in them.


[#45245] Thursday, May 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelyn

Total Points: 619
Total Questions: 102
Total Answers: 104

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;