Unable to retrieve MongoDB attributes or methods

I'm attempting to access properties or functions within mongoose.connection in order to retrieve the DeleteMany and DropCollection methods, but I seem to be unable to do so. I am initiating the express.js server inside the mongoose connection.

mongoose
.connect(connection, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
    mongoose.connection.db.dropCollection('database');
    console.log('connected');
    app.listen(5000);
})
.catch((error) => {
    console.log(error);
});

What is my mistake? I have tried searching for a solution and understand that I cannot delete a collection using Mongoose, only data using MongoDb. Can someone please help me understand what I might be missing when trying to delete the collection when the server is running?

Answer №1

If you need to remove all entries using the deleteMany method in mongoose.

You must specify the model of the collection where the operation will be applied

To delete a collection entirely

MyModel.collection.drop();

Removing all entries

const mongoose = require('mongoose'); 
  
// Establishing database connection
mongoose.connect(connectionUrl, { 
    useNewUrlParser: true,
    useUnifiedTopology: true
}); 
  
// Creating MyCollection model 
const MyCollection = mongoose.model('MyCollection', { 
    prop1: { type: String }, 
    prop2: { type: Number } 
}); 
  
// Invoking the function 
MyCollection.deleteMany({}).then(function(){ 
    console.log("all records deleted"); // Successful deletion 
}).catch(function(error){ 
    console.log(error); // Deletion failed 
}); 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When working with ASP.NET MVC 3, be aware that the ContentResult may not accept a class that inherits from

After my previous question regarding finding nearby entities with Bing Maps REST control, I have made some modifications. Within the for loop of the function DisplayResults(response), the following code has been added: var loc = new Array(); loc[0 ...

Pressing the ENTER key does not submit the text box data in Rails/Bootstrap, but clicking the SUBMIT button does

I need assistance with my Rails 4 and Bootstrap 3 project. I have implemented an email address field on my page (localhost:3000) where users can enter their email and click the SUBMIT button to send it to the MongoDB database. However, pressing the ENTER k ...

Retrieve the identification of elements with dynamically generated ids

I've dynamically generated a set of elements using Handlebars, as shown below {{#floor as |room i|}} <div class="btn-group-toggle" data-toggle="buttons" > <label class="btn btn-secon ...