1

我在 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 错误:

要求语句不是导入语句的一部分。eslint

而且我不能使用delete功能。它没有在 mongoose.Dcoument 中定义

  export type ChannelDocument = Channel & Document;

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

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

4

2 回答 2

0

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

于 2022-01-13T20:02:16.580 回答
-1

请看一下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();
}
于 2021-05-24T04:21:13.793 回答