I need to insert some data into my db using mongoose but the name of the collection to get the data is provided by the user at the moment of the insert so I first need to check if the name is valid (i.e. a collection with that name exists in the db).
The way I know of to check if a collection exists is by querying the system.namespaces
collection and I can see 3 possible approaches to doing that.
system.namespaces
using mongoose (maybe defining a
schema that matches the one in the db).Number 3
is the least elegant and the one i'm trying to avoid, I don't want to load another instance of the driver nor create a new connection when mongoose already created some.
I'm going to try with 1
after writing this since I just checked the system.namespaces collection and the schema looks quite simple
But nevertheless I would like what to know what would be a good approach in this case.
Thanks!
Option 2 is probably the cleanest. Assuming you have a Mongoose Connection
object named conn
that's been opened using mongoose.createConnection
, you can access the native mongo Db
object via conn.db
. From there you can call collectionNames
which should provide what you're looking for:
conn.db.collectionNames(function (err, names) {
// names contains an array of objects that contain the collection names
});
You can also pass a collection name as a parameter to collectionNames
to filter the results to just what you're looking for.
Mongoose 4.x Update
In the 2.x version of the MongoDB native driver that Mongoose 4.x uses, collectionNames
has been replaced by listCollections
which accepts a filter and returns a cursor so you would do this as:
mongoose.connection.db.listCollections({name: 'mycollectionname'})
.next(function(err, collinfo) {
if (collinfo) {
// The collection exists
}
});
Find collection in collection's list
public function CollectionExists($collectionName)
{
$mongo = new Mongo();
$collectionArr = $mongo->selectDB('yourrec')->listCollections();
if (in_array($collectionName, $collectionArr)) {
return true;
}
return false;
}