fatiu
fatiu

Reputation: 1538

I need help referencing id declared in the @Schema property in nestJs

I have a schema that uses the @Schema to define _id and timestamp as shown below:

@Schema({
id: true,
timestamps: {
    createdAt: 'createdAt',
    updatedAt: 'updatedAt',
},
})

export class Account {
@Prop({
    type: String,
    enum: Roles,
    required: true,
})
role?: string;

@Prop({
    type: String,
    required: false,
})
businessName?: string;

}

I want to use reference the Account id in a function but since its not explicitly defined, I am stuck on it.

await this.userService.updateAccount(
                { _id: filter._id },
                { outlet: findInvite.outlet._id }, //Property '_id' does not exist on type 'Outlet'.ts(2339)

                '_id',
            );
            return;
        }

Upvotes: 2

Views: 589

Answers (2)

Ernest
Ernest

Reputation: 46

Also you can just solve by placing virtuals in true inside toObject and the id attribute as optional inside the class. After the transformation from Schema to Object you will be able to access the id. In this case you don't need use the transform function.

(By the way... note in my example that I also use toJSON option, that's also very useful for removing attributes that you don't want to send in the API response, such as user's password)

@Schema({
  timestamps: true,
  toJSON: {
    virtuals: true,
    transform(doc, ret) {
      delete ret._id;
      delete ret.__v;
      delete ret.password;
    },
  },
  toObject: {
    virtuals: true,
  },
})
export class User {
  id?: string;

  @Prop({ required: true, trim: true })
  name: string;

  @Prop({ required: true, unique: true, lowercase: true })
  email: string;

  ...
}

Upvotes: 1

Ernest
Ernest

Reputation: 46

To solve this problem I created an attribute inside the class like "id ?: string" and I assign the value to it when transforming the Schema into an Object, inside the Schema decorator you will see that there are two functions to be able to modify the Schema to time to pass it to JSON (when returned as API response) and to Object:

@Schema({
  timestamps: true,
  toJSON: {
    virtuals: true,
    transform(doc, ret) {
      delete ret._id;
      delete ret.__v;
    },
  },
  toObject: {
    virtuals: true,
    transform(doc, ret) {
      doc.id = ret._id;
    },
  },
})
export class User {
  id?: string;

  @Prop({ required: true, trim: true })
  name: string;

  @Prop({ required: true, unique: true, lowercase: true })
  email: string;

  ...
}

Upvotes: 2

Related Questions