[英]How to use `mongoose-delete` plugin with NestJs and typescript?
我在 NestJs 庫中使用 Mongoose 並希望對我的所有模式使用 mongoose -delete插件。
首先,我同時安裝了mongoose-delete
和@Types/mongoose-delete
庫,但是這個插件沒有 typescript 文檔。 這是嵌套添加插件的推薦方法:
MongooseModule.forRoot(MONGO_URI, {
connectionFactory: connection => {
connection.plugin(require('mongoose-delete'));
return connection;
},
}),
這絕對會產生 esLint 錯誤:
Require 語句不是 import statement.eslint 的一部分
而且我不能使用delete
function。它沒有在 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 -^
}
請看一下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();
}
安裝此 package 后,嘗試重新啟動 IDE(如果使用 vscode):@types/mongoose-delete
使用軟刪除插件 => https://www.npmjs.com/package/soft-delete-mongoose-plugin
一個簡單友好的mongoose軟刪除插件,使用TS實現。 在 mongoose model 上添加和重寫方法,實現軟刪除邏輯。
yuo 可以用作全局插件:
import { plugin } from 'mongoose';
import { SoftDelete } from 'soft-delete-mongoose-plugin';
// defind 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
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.