首页 > 解决方案 > 如何在 NestJs 和 Mongoose 中播种数据?

问题描述

我在 Mongodb 中有收藏shopsproducts

商店模式

@Schema({ timestamps: true })
export class Shop extends Document {
  @Prop({ required: true, index: { unique: true } })
  id: string;

  @Prop({ required: true, index: { unique: true } })
  shop: string;

  @Prop({ required: true })
  accessToken: string;

  @Prop({ required: true })
  scope: string;

  @Prop({ type: Date })
  expires: Date;

  @Prop({ type: Boolean })
  isOnline: boolean;

  @Prop({ type: String })
  state: string;
}

export const ShopSchema = SchemaFactory.createForClass(Shop);

产品架构

@Schema({ timestamps: true })
export class Product extends Document {
  @Prop({ required: true, index: {unique: true} })
  id: string

  @Prop({ required: true })
  title: string

  @Prop({ required: true })
  desc: string

  @Prop({ required: true })
  price: number

  @Prop({ required: true })
  stock: number

  @Prop({ type: mongooseSchema.Types.ObjectId, ref: 'Shop', required: true })
  shopId: mongooseSchema.Types.ObjectId;
}

export const ProductSchema  = SchemaFactory.createForClass(Product);

现在我想在添加products新数据时将一些虚拟数据(来自 json)播种到集合shop中。我已经使用过 Nestjs 命令,它运行良好。但是我不想通过使用命令来播种数据,所以我尝试了 Nestjs 生命周期事件方法(这不是正确的方法)。谁能推荐我任何其他方法?

我听说我们可以使用 Mongoose 钩子。如果可以,请任何人解释一下。

标签: node.jsmongodbmongoosenestjs

解决方案


推荐阅读