Initialize and save multiple related documents together in nestjs and mongoose

48 Views Asked by At

Database Design

I have attached photos!

Hello, I have the following case: I want to automatically create a user after creating an account and save it to the database. I am using mongoose and nestjs, I have written the following schema:

// Account Schema
export type AccountDocument = HydratedDocument<Account>

@Schema()
export class Account {
  // @Prop()
  // id: string;

  @Prop({ required: true, unique: true, immutable: true })
  username: string;

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

  @Prop({ required: true, default: false, immutable: true })
  isAdmin: boolean;

  @Prop({
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    unique: true
  })
  user: User;
}

export const AccountSchema = SchemaFactory.createForClass(Account)

//User schema
export type UserDocument = HydratedDocument<User>

@Schema()
export class User {
  // @Prop()
  // id: string;

  @Prop({ required: false })
  displayName: string;

  @Prop({ required: false })
  address: string;

  @Prop({ required: false })
  phoneNumber: string;

  @Prop({ required: false, enum: genderEnum })
  gender: genderEnum;

  @Prop({ required: false })
  avatar: string;

  @Prop({
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Account',
    unique: true
  })
  account: Account
}

export const UserSchema = SchemaFactory.createForClass(User)

I'm trying to find a way to automatically create a user associated with this account when creating an account. Thanks for your help

1

There are 1 best solutions below

0
R Simioni On

You need to initialize the user property when creating a new Account

Mongoose won't initialize subdocuments if they are undefined, but if you set them to any truthy value (even an empty object), mongoose will apply the default values from the schema to this subdocument.

const accountDoc = new Account(...data)
accountDoc.user = {} // <- set this
await accountDoc.save()
console.log(accountDoc.user._id) // <- ObjectID

From the docs: Subdocument defaults.