作者:sjf66355555 | 来源:互联网 | 2023-08-07 14:05
本文由编程笔记#小编为大家整理,主要介绍了Javascript 删除猫鼬的级联相关的知识,希望对你有一定的参考价值。
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 ');
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);
})();