Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created July 25, 2018 12:34
Show Gist options
  • Save sibelius/9fc728cd4557bcf9f0f3dd8eb2835948 to your computer and use it in GitHub Desktop.
Save sibelius/9fc728cd4557bcf9f0f3dd8eb2835948 to your computer and use it in GitHub Desktop.
Remove cascade for mongoose
import mongoose from 'mongoose';
import connectDatabase from '../src/common/database';
// this is needed to load all models in mongoose.models
// eslint-disable-next-line
import * as M from '../src/models';
const removeCascade = async (modelName: string, _id: string) => {
const modelNames = Object.keys(mongoose.models);
// get all mongoose models
for (const name of modelNames) {
const { paths } = mongoose.models[name].schema;
const pathKeys = Object.keys(paths);
// check if there any path/field that reference the modelName
for (const path of pathKeys) {
if (paths[path].options.ref === modelName) {
// remove all references of this _id in references models
const rows = await mongoose.models[name].find({
[path]: _id,
});
if (rows.length > 0) {
for (const row of rows) {
// remove references of references
await removeCascade(name, row._id);
}
// eslint-disable-next-line
console.log(`remove ${modelName} ${_id} from ${name} ${path}`);
await mongoose.models[name].remove({
[path]: _id,
});
}
}
}
}
// eslint-disable-next-line
console.log(`remove ${modelName} ${_id}`);
await mongoose.models[modelName].remove({
_id,
});
};
//mongoose.models.User.schema.paths.user.options.ref
(async () => {
try {
if (process.argv.length !== 4) {
// eslint-disable-next-line
console.log('usage: yarn babel-node ./scripts/removeCascadeMongo.js <modelName> <modelId>');
return;
}
const modelName = process.argv[2];
const _id = process.argv[3];
await connectDatabase();
await removeCascade(modelName, _id);
} catch (err) {
// eslint-disable-next-line
console.log('err: ', err);
}
process.exit(0);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment