使用猫鼬和nestJS自动增加字段
Posted
技术标签:
【中文标题】使用猫鼬和nestJS自动增加字段【英文标题】:Autoincrement of field with mongoose and nestJS 【发布时间】:2020-10-15 12:22:59 【问题描述】:有人可以指导我如何在使用 mongoose 和 nestJS 框架时自动增加集合中的任何字段。
例如:假设我有这个用户架构
@Schema()
export class User extends Document
@Prop()
userId: number; // I want to increment this field on each new user
@Prop()
name: string;
@Prop(
type: String,
required: true,
unique: true,
)
email: string;
@Prop()
isEmailVerified: boolean;
@Prop(
type: String,
required: true,
unique: true,
)
mobile: string;
@Prop()
isMobileVerified: boolean;
@Prop(
type: String,
required: true,
)
password: string;
export const UserSchema = SchemaFactory.createForClass(User);
我想在每个新用户上增加 userId。谢谢
【问题讨论】:
我猜这是重复的问题,请检查create-unique-autoincrement-field-with-mongoose nestJs 的架构与 node.js 几乎没有什么不同。我已经尝试过这个东西,但我无法弄清楚,我如何在nestJS中应用同样的东西。 【参考方案1】:Schema 装饰器有一个 SchemaOptions 类型的 options 参数:
@Schema( timestamps: true )
如果要重命名时间戳:
@Schema( timestamps: createdAt: 'created_at', updatedAt: 'updated_at' )
【讨论】:
【参考方案2】:编辑
因为您要求提供代码示例...我正在使用带有此库 ts-mongoose-pagination
的打字稿来管理卡片架构上的分页内容,顺便说一句,我正在使用 Nestjs
card.sceham.ts
import Schema, Types from 'mongoose';
import CardTypesEnum from '../utils/constants';
import mongoosePagination from "ts-mongoose-pagination";
const CardSchema = new Schema(
isOriginal: Boolean,
parentCard: type: Types.ObjectId, ref: 'Card',
patientId: String,
coverImage: String,
title: String,
content: String,
createdBy: String,
tags: [String],
type:
type: String,
default: CardTypesEnum.NORMAL,
enum: Object.values(CardTypesEnum),
,
,
timestamps: true,
);
CardSchema.plugin(mongoosePagination);
export CardSchema;
app.module.ts
import Module from '@nestjs/common';
import AppController from './app.controller';
import CardService from './card.service';
import ScheduleModule from '@nestjs/schedule';
import MongooseModule from '@nestjs/mongoose';
import CardSchema from './schemas/card.shcema';
import * as config from 'config';
const DB_HOST = config.get('DB');
@Module(
imports: [
MongooseModule.forRoot(process.env.DB || DB_HOST,
useNewUrlParser: true,
useUnifiedTopology: true,
),
MongooseModule.forFeature([
name: 'Card',
schema: CardSchema,
]),
ScheduleModule.forRoot()],
controllers: [AppController],
providers: [CardService],
)
export class AppModule
card.service.ts
import Injectable, Logger from '@nestjs/common';
import InjectModel from '@nestjs/mongoose';
import IPaginateResult, Model, PaginateModel from 'mongoose';
import CardsListFilterDto, CardDto from './utils/dto/Cards.dto';
import QueryOptionsDto from './utils/dto/db.dto';
@Injectable()
export class CardService
private readonly logger = new Logger(CardService.name);
constructor(
// cardModel type is not Model but PaginateModel (so you can use the paginate method)
@InjectModel('Card') private readonly cardModel: PaginateModel<any>,
)
async getCardLists(cardsListFilterDto: CardsListFilterDto): Promise<IPaginateResult<any>>
const optionsDto: QueryOptionsDto =
page: parseInt(cardsListFilterDto.page),
perPage: parseInt(cardsListFilterDto.perPage),
sort: '_id': -1
;
const where =
createdBy: cardsListFilterDto.createdBy,
isOriginal: true,
;
// you can have paginate method by adding the plugin to schema
return await this.cardModel.paginate(where, optionsDto)
希望这能解决您的问题
【讨论】:
是的,我知道插件,我只是想了解这些插件在 Nest js 中的实现。你能给我一些代码示例吗? @SiddharthChandra 我已经编辑了完整 Nestjs 示例的答案,看看 我了解如何应用带有模式的插件。如果插件需要数据库连接对象怎么办?自动增量插件需要数据库连接才能工作。以上是关于使用猫鼬和nestJS自动增加字段的主要内容,如果未能解决你的问题,请参考以下文章