jviotti
jviotti

Reputation: 18919

Checking if Mongoose DB is empty

I know I cant query the db with find method and checks if it returns an empty array, but is there any specific method in Mongoose to check if the DB has no objects in it?

Upvotes: 3

Views: 2299

Answers (2)

smartmouse
smartmouse

Reputation: 14404

You should consider that you are dealing with an asynchronous call, so you should use this:

collection.countDocuments(function (err, count) {
    if (!err && count === 0) {
        // It's empty
    }
});

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311885

In the mongo shell you could just do:

 if (db.getCollectionNames().length === 0) {
     // It's empty
     ...
 }

Each language's driver should have something equivalent.

Upvotes: 3

Related Questions