mongoose使用对象ID进行软删除

时间:2017-04-07 11:15:38

标签: node.js mongoose soft-delete

所以我试图使用mongoose-delete插件来软删除mongoDB中的数据,但是请求只获得了mongoose对象的对象ID。所以为了"软删除"数据,我不得不首先做一个findOne,然后使用删除功能。是否有任何插件或功能可以让我仅使用对象ID软删除此数据?而不是使用两个命中数据库。数据很关键,因此只需要一个软删除选项,而不是硬删除。我不能使用通用更新功能,需要一些插件或节点模块来为我做这个。

4 个答案:

答案 0 :(得分:4)

您不需要任何库,使用中间件和$ isDeleted文档方法编写自己很容易

示例插件代码:

import mongoose from 'mongoose';

export type TWithSoftDeleted = {
  isDeleted: boolean;
  deletedAt: Date | null;
}

type TDocument = TWithSoftDeleted & mongoose.Document;

const softDeletePlugin = (schema: mongoose.Schema) => {
  schema.add({
    isDeleted: {
      type: Boolean,
      required: true,
      default: false,
    },
    deletedAt: {
      type: Date,
      default: null,
    },
  });

  const typesFindQueryMiddleware = [
    'count',
    'find',
    'findOne',
    'findOneAndDelete',
    'findOneAndRemove',
    'findOneAndUpdate',
    'update',
    'updateOne',
    'updateMany',
  ];

  const setDocumentIsDeleted = async (doc: TDocument) => {
    doc.isDeleted = true;
    doc.deletedAt = new Date();
    doc.$isDeleted(true);
    await doc.save();
  };

  const excludeInFindQueriesIsDeleted = async function (
    this: mongoose.Query<TDocument>,
    next: mongoose.HookNextFunction
  ) {
    this.where({ isDeleted: false });
    next();
  };

  const excludeInDeletedInAggregateMiddleware = async function (
    this: mongoose.Aggregate<any>,
    next: mongoose.HookNextFunction
  ) {
    this.pipeline().unshift({ $match: { isDeleted: false } });
    next();
  };

  schema.pre('remove', async function (
    this: TDocument,
    next: mongoose.HookNextFunction
  ) {
    await setDocumentIsDeleted(this);
    next();
  });

  typesFindQueryMiddleware.forEach((type) => {
    schema.pre(type, excludeInFindQueriesIsDeleted);
  });

  schema.pre('aggregate', excludeInDeletedInAggregateMiddleware);
};

export {
  softDeletePlugin,
};

您可以将其用作全局插件或指定架构的插件

答案 1 :(得分:2)

您可以使用mongoose-delete:https://github.com/dsanel/mongoose-delete

它提供了新的delete功能。

答案 2 :(得分:0)

您可以使用Mongoosejs Soft delete。查看GitHub Repository上的代码。

答案 3 :(得分:0)

我知道有点晚了。但是,我希望这可以帮助那里的人

这是一个兼容 JS & TS 的 npm 包,用于软删除元素并使用 mongoose 恢复它们

https://www.npmjs.com/package/soft-delete-plugin-mongoose

相关问题