Extracting attribute names from a model's schema in Dynamoose v3: A guide

Exploring dynamoosev2:

T extends Document; model: ModelType<T>;

const attributes: string[] = model.schemas[0].attributes();

Is there a different approach to retrieve attribute names from the model in dynamoose v3?

Transitioning to dynamoose v3:

T extends Item; model: ModelType<T>;

const attributes: string[] = model.schemas[0].attributes();

An error emerges stating:

Property 'schemas' does not exist on type 'ModelType<T>'
.

Answer №1

When I was working with Dynamoose 3, I faced a similar issue. Below is a demonstration of how to retrieve model attributes:

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

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

If you try to create a new record with an undeclared field like surname, TypeScript will show an error.

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

After creating or fetching the model, your IDE will provide you with the correct 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)

Answer №2

Accessing internal properties directly is not possible in dynamoose v3, as they are only accessible through the private function #getInternalProperties.

To work around this limitation, you can export both the Model and schema definition like so:

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
  },
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to using the ng-click function in Angular to set focus on the input in the last row of a table

I am in the process of developing a task management application and I am looking to implement a specific feature: Upon clicking 'Add Task', a new row is automatically added to the table (this part has been completed) and the input field within ...

Unable to show the image within the designated cropping zone

Having trouble displaying the image in the cropper. The image URL is set as the source attribute in the HTML, but the image isn't showing up. When I click the edit button, I want to show the current image (the one above the edit button) in the cropper ...

Leverage third-party extensions instead of ionic-native plugins in your Ionic 2

Currently, I am utilizing a Cordova plugin from GitHub that is not accessible in Ionic Native. However, I have encountered an issue. How can I effectively use non-Ionic-Native plugins in Ionic 2? I attempted the following: declare var myPlugin: any; my ...

File uploading from Angular to Node.js backend encountering issues with reading file data

I'm currently using Angular file upload with Laravel Lumen in the past for the backend, but now I've switched to Node and I'm having trouble retrieving the file contents after an upload. ANGULAR FRONT END $scope.upload = Upload.upload({ ...

Why is jshint giving an error for HTML in $scope in Angular JS?

I need help figuring out how to include HTML tags in my model. Here is a basic example where I am trying to include b tags: .controller('AccordionDemoCtrl', ['$scope', function($scope) { $scope.oneAtATime = true; ...

Incorporating grids for a flickering drag and drop effect in Javascript

I have been working on developing a selection system for a tilemap image where users can select multiple tiles by dragging the mouse to increase the size of the selection container. However, I've noticed a flickering effect while holding down the mous ...

"Enhance Your Website's User Experience with jQuery Aut

One of the challenges I am facing involves an Ajax call that retrieves a JSON representation of data created using PHP's json_encode method: ["Montérégie","Montréal - North Shore","Montréal - South Shore"] These values are extracted from a &apos ...

Adjusting a polyline in Google Maps

I've successfully used Google Maps V3 API to create a polyline with 2 points. However, I now need to shorten the polyline. Issue: My goal is to make the polyline extend from the start point to the midpoint between the start and end points. How can I ...

Error: The projection option used with $elemMatch is not supported in this context

I have a topic model: const topicSchema = new Schema({ name: String, details: { currentSection: { title: String, subtopics: [String], }, sections: [ { title: String, subtopics: [String], }, ], } ...

What is the process of altering the permissions of a text channel dynamically in Discord.js?

I'm currently developing a small bot that aims to grant users in a voice channel access to a designated channel for individuals without microphones, and then automatically remove the channel once they're done. While I've managed to successf ...

Is there a way to adjust the scrolling speed of a background image to be slower than the rest of

I'm searching for an example similar to this: Are there any efficient javascript solutions available? I've had difficulty implementing the code I've come across so far. ...

Building a straightforward RESTful API for user authentication with Node.js, MongoDB, and Express.js

Can someone provide guidance on creating a RESTful API using Node.js, Express.js, and MongoDB? Specifically, I am looking for assistance with writing the schema for login and sign up pages, as well as comparing data in MongoDB using Node.js Express.js. As ...

Differences in behavior of constructors when utilizing ES6 shorthand notation

ES6 introduced a new way to initialize objects with functions and properties using shorthand notation. // ES6 shorthand notation const obj1 = { a(b) { console.log("ES6: obj1"); } }; // ES5 var obj2 = { a: function a(b) { con ...

JavaScript - Function is not recognized even though it has been defined, following the completion of a jQuery function

I am encountering an 'Is Undefined' error when running a piece of JavaScript code. https://i.sstatic.net/q3EfY.png < script language = "javascript" type = "text/javascript" > // function added for click on submit - dp0jmr 05/23/20 ...

Steps for generating a JSON request from XPages to the Yandex Translate API

Can anyone assist me in creating a JSON request from XPages to the Yandex JSON interface API? I need help with configuring the HTTPS request for this specific API. More information can be found at this link. Additionally, I am looking for guidance on how ...

When delving into an object to filter it in Angular 11, results may vary as sometimes it functions correctly while other times

Currently, I am working on implementing a friend logic within my codebase. For instance, two users should be able to become friends with each other. User 1 sends a friend request to User 2 and once accepted, User 2 is notified that someone has added them a ...

Steps to deactivate the submission button within a modal containing a ReactJS child form

Could someone help me out with disabling the action buttons in a modal while the form is submitting? I haven't been able to find a solution online since I have limited experience with Javascript and React. Here is the project structure: Countries li ...

The best way to access the value of a fulfilled Promise while debugging

I've been using this loopback application in my IntelliJ IDE. I set a breakpoint at the promise in calculator.controller.ts, where the code looks like this: @get('/multiply/{intA}/{intB}') async multiply( @param.path.integer('in ...

Unraveling the mysteries of an undefined entity

When the variable response is undefined, attempting to retrieve its property status will result in an error: Error: Unable to access property 'status' of undefined const { response, response: { status }, request, config, } = error as A ...

Access key-value pairs of objects without the use of the keyword "as"

const resources = { background: '', player: '', }; const totalResourceCount = Object.keys(resources).length; type resourceKey = keyof typeof resources; export class ResourceLoader { images: Record<resourceKey, HTMLImageElemen ...