javascript 删除猫鼬的级联

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 <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);
})();

以上是关于javascript 删除猫鼬的级联的主要内容,如果未能解决你的问题,请参考以下文章

没有级联删除目标的级联删除关系

Mongoose中的级联样式删除

Mongoose中的级联样式删除

如何在 EF 代码优先中禁用链接表的级联删除?

SQL中的级联菱形删除

删除性能的级联:删除一行其 1-Many 行的最快方法是啥?