因此,我尝试使用mongoose-delete插件来软删除mongoDB中的数据,但请求只获得了mongoose对象的对象ID。因此,为了“软删除”数据,我必须首先执行findOne,然后对其使用delete函数。有没有什么插件或函数可以让我只用对象ID就能软删除这些数据?而不是使用两次命中数据库。数据是关键的,因此只需要软删除选项,而不是硬删除。而且我不能使用通用的更新功能,需要一些插件或节点模块来为我做这件事。
发布于 2020-05-25 22:53:59
您不需要任何库,使用中间件和$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,
};
您可以将其用作全局插件或指定模式的插件
发布于 2017-04-07 19:22:23
您可以使用mongoose-delete:https://github.com/dsanel/mongoose-delete。
它提供了新的delete
函数。
发布于 2018-12-02 13:32:42
您可以使用Mongoosejs Soft delete。看看GitHub Repository上的代码。
https://stackoverflow.com/questions/43276776
复制相似问题