Skip to content

Instantly share code, notes, and snippets.

@sdgluck
Last active August 14, 2016 17:03
Show Gist options
  • Save sdgluck/950cb9c8af974992e3eb to your computer and use it in GitHub Desktop.
Save sdgluck/950cb9c8af974992e3eb to your computer and use it in GitHub Desktop.
Drop a collection with mongoose and remove internal references. Returns a Promise.
function dropCollection (modelName) {
if (!modelName || !modelName.length) {
Promise.reject(new Error('You must provide the name of a model.'));
}
try {
var model = mongoose.model(modelName);
var collection = mongoose.connection.collections[model.collection.collectionName];
} catch (err) {
return Promise.reject(err);
}
return new Promise(function (resolve, reject) {
collection.drop(function (err) {
if (err) {
reject(err);
return;
}
// Remove mongoose's internal records of this
// temp. model and the schema associated with it
delete mongoose.models[modelName];
delete mongoose.modelSchemas[modelName];
resolve();
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment