How to get schema attributes names from model in dynamoose v3?

435 views Asked by At

In dynamoose v2:

T extends Document; model: ModelType<T>; const attributes: string[] = model.schemas[0].attributes();

In this way I get the attributes names of the schema. How I can get attributes names from model in dynamoose v3?

In dynamoose v3:

T extends Item; model: ModelType<T>; const attributes: string[] = model.schemas[0].attributes();

I have the following error: Property 'schemas' does not exist on type 'ModelType<T>'.

2

There are 2 answers

0
Hyder B. On

I encountered a similar issue while working with Dynamoose 3. Here's a working example how to get model attributes:

import * as dynamoose from "dynamoose";
import {Item} from "dynamoose/dist/Item";

// Strongly typed model
class Person extends Item {
    id: number;
    name: string;
}
const PersonModel = dynamoose.model<Person>("Person", {"id": Number, "name": String});

If you attempt to create a new record with an undeclared field e.g surname, Typescript will yell at you.

CatModel.create({"id": 1, "surname": "string"});

After creating or fetching the model, your IDE will correctly provide you the attributes.

Example 1:

const Person = await PersonModel.get(1);
//console.log(Person.id)
//console.log(Person.name)

Example 2:

const Person = await PersonModel.create({id: "1", name: "John" })
//console.log(Person.id)
//console.log(Person.name)
0
Kome On

It is impossible, because all the internal properties are only accessible by private function #getInternalProperties in dynamoose v3.

One of the workarounds is to export not only Model but also schema definition like this.

export const UserSchema: SchemaDefinition = {
  id: {
    type: String,
    required: true,
    hashKey: true,
  },
};
export const UserModel = dynamoose.model(
  "TableName",
  [new dynamoose.Schema(UserSchema, { timestamp: true })],
  {
    // some setting for model
  },
);