mongodb 如何使用`mongoose-delete`插件与NestJs和typescript?

lztngnrs  于 2023-04-29  发布在  Go
关注(0)|答案(3)|浏览(139)

我在NestJs库中使用Mongoose,并希望为我的所有模式使用mongoose-delete插件。

但我不知道如何使用它与nestJS和Typescript。

首先,我安装了mongoose-delete@Types/mongoose-delete库,但没有此插件的类型脚本文档。这是通过嵌套添加插件的推荐方法:

MongooseModule.forRoot(MONGO_URI, {
      connectionFactory: connection => {
        connection.plugin(require('mongoose-delete'));
        return connection;
      },
    }),

这绝对会生成esLint错误:
Require语句不是import语句的一部分。埃斯林特
而且我不能使用delete函数。 Mongoose 没有定义。德库芒

export type ChannelDocument = Channel & Document;

  constructor(
    @InjectModel(Channel.name) private _channelModel: Model<ChannelDocument>,
  ) {}

  async delete(id: string) {
    this._channelModel.delete({ id });
    // This is undefined -^
  }
qlckcl4x

qlckcl4x1#

使用软删除插件=〉https://www.npmjs.com/package/soft-delete-mongoose-plugin
一个简单友好的Mongoose软删除插件,用TS实现。在Mongoose模型上增加和重写方法实现软删除逻辑。
您可以将其用作全局插件:

import { plugin } from 'mongoose';
import { SoftDelete } from 'soft-delete-mongoose-plugin';

// define soft delete field name
const IS_DELETED_FIELD = 'isDeleted';
const DELETED_AT_FIELD = 'deletedAt';

// Use soft delete plugin
plugin(
  new SoftDelete({
    isDeletedField: IS_DELETED_FIELD,
    deletedAtField: DELETED_AT_FIELD,
  }).getPlugin(),
);

// other code
// ...
lxkprmvk

lxkprmvk2#

安装此软件包后尝试重新启动IDE(如果使用vscode):@types/mongoose-delete

rsl1atfo

rsl1atfo3#

请查看mongoose-softdelete-typescript

import { Schema, model } from 'mongoose';
import { softDeletePlugin, ISoftDeletedModel, ISoftDeletedDocument } from 'mongoose-softdelete-typescript';

const TestSchema = new Schema({
  name: { type: String, default: '' },
  description: { type: String, default: 'description' },
});

TestSchema.plugin(softDeletePlugin);

const Test = model<ISoftDeletedDocument, ISoftDeletedModel<ISoftDeletedDocument>>('Test', TestSchema);
const test1 = new Test();
// delete single document
const newTest = await test1.softDelete();
// restore single document
const restoredTest = await test1.restore();
// find many deleted documents
const deletedTests = await Test.findDeleted(true);
// soft delete many documents with conditions
await Test.softDelete({ name: 'test' });

// support mongo transaction
const session = await Test.db.startSession();
session.startTransaction();
try {
  const newTest = await test1.softDelete(session);

  await session.commitTransaction();
} catch (e) {
  console.log('e', e);
  await session.abortTransaction();
} finally {
  await session.endSession();
}

相关问题