how to create nested schema in nestjs use mongodb

392 Views Asked by At
  • email
  • password
  • role
  • confirmed
  • id
  • address
    • city
    • street

My user schema should be like this. I want it to appear as a nested schema. separate the address space.

export const UserSchema = new mongoose.Schema({
  email: { type: String, unique: true, required: true },
  password: { type: String, required: true },
  role: { type: String, enum: Role, default: Role.USER },
  confirmed: { type: Boolean, default: false },
  id: { type: String, default: uuid.v4 },
});

UserSchema.pre('save', async function (next) {
  try {
    if (!this.isModified('password')) {
      return next();
    }
    const hashed = await bcrypt.hash(this['password'], 10);
    this['password'] = hashed;
    return next();
  } catch (err) {
    return next(err);
  }
});

interface user

export interface User extends Document {
   id:string;
   email: string;
   password: string;
   role: Role[];
   address: ?
}

I have to add the address in user. How?

  export const AddrSchema= new mongoose.Schema({
      city: { type: String, default: "bb" },
      street: { type: String, default: "aa" },
    })
1

There are 1 best solutions below

3
On

I think this will solve it.

 export const UserSchema = new mongoose.Schema({
   email: { type: String, unique: true, required: true },
   password: { type: String, required: true },
   role: { type: String, enum: Role, default: Role.USER },
   confirmed: { type: Boolean, default: false },
   id: { type: String, default: uuid.v4 },
   address: { 
     city: { type: String, default: "bb" },
     street: { type: String, default: "aa" },
   }
  });