Berkin
Berkin

Reputation: 1664

Mongoose Check If Collection Exist

I'm trying insert 800 objects into mongodb also I'm trying to prevent inserting same elements again and again. I will check if collection exist, don't insert, else insert 800 objects.

mongoose.connect('mongodb://localhost/testDB', function(err,db){
  if(err){
    console.log(err)
  }
  db.listCollections().toArray(function(err, collections){
    console.log(collections);
  });
});

But console throws and error and it says:

(node:24452) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: db.listCollections is not a function
(node:24452) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I'm stuck right now, thanks.

Upvotes: 1

Views: 2568

Answers (1)

Grigory Babajanyan
Grigory Babajanyan

Reputation: 195

listCollections function is available on client.db, have you tried this?

mongoose.connect('mongodb://localhost/testDB', function(err, client) {
    if(err) {
        console.log(err)
    }

    client.db.listCollections().toArray(function(err, collections) {
        console.log(collections);
    });
});

Upvotes: 2

Related Questions