node.js - 如何在 NestJs 和 Mongoose 中播种数据?
问题描述
我在 Mongodb 中有收藏shops
。products
商店模式
@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 钩子。如果可以,请任何人解释一下。
解决方案
推荐阅读
- sql - 如何从“select *”输出中查看 TDengine 数据库中的最新行?
- javascript - 如何在 Angular 中使用 2 种方式的数据绑定?
- java - 在方法中实现带有附加参数的接口
- internet-explorer - 当用作 ActiveX 控件时,有没有办法调试 shdocvw.dll?
- c# - 如何在 c# 中覆盖 System.Convert.Tostring 方法
- reactjs - 将表单数据发送到后端
- visual-studio-code - 如何取回 VS Code 中 jupyter NB 中的“在下方插入单元格”按钮?
- openid-connect - OrchardCore OpenId /authorize 重定向到 http(而不是 https)
- hyperledger-fabric - 将新组织添加到通道后的 Hyperledger Fabric 警告
- python - 原生移动应用程序是否需要 Web 服务器?