Utilizing TypeScript code to access updatedAt timestamps in Mongoose

When querying the database, I receive the document type as a return.

const table: TableDocument = await this.tableSchema.create({ ...createTableDto })
console.log(table)

The structure of the table object is as follows:

{
  createdBy: '12',
  capacity: 4,
  tableNumber: 5,
  _id: new ObjectId("618bdb1ab2e5813b6f1fc198"),
  createdAt: 2021-11-10T14:45:46.279Z,
  updatedAt: 2021-11-10T14:45:46.279Z,
  __v: 0
}

However, I am facing an issue accessing the updatedAt property in my code.

table.__v exists

table.updatedAt does not exist on this type: TableDocument

If possible, I would like to declare to TypeScript that I am returning a custom type:

const table: ResponseTable = await this.tableSchema.create({ ...createTableDto })

Although the error "Table Document is not assignable to ResponseTable..." occurs.

I am struggling to find a solution with Mongoose 6.0 TypeScript support

Answer №1

After giving it some thought, I came up with a solution:

export type TableDocument = Table & Document & {updatedAt: Date, createdAt: Date}

Essentially, once I define the TableDocument type following the creation of the Schema class Table, I simply append the updatedAt and createdAt properties to it. This way, when mongoose indicates that it is returning a TableDocument, Typescript recognizes these additional fields for utilization.

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

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

Using Vue-router and Typescript with beforeEnter guard - utilizing validated data techniques

As I utilize Vue along with vue-router and typescript, a common scenario arises where a single page is dedicated to displaying a Photo component. A route includes a beforeEnter guard that checks my store to verify the existence of the requested photo. ...

Is it possible to implement a redirect in Angular's Resolve Navigation Guard when an error is encountered from a resolved promise?

I have integrated Angularfire into my Angular project and am utilizing the authentication feature. Everything is functioning properly, however, my Resolve Navigation Guard is preventing the activation of the component in case of an error during the resolve ...

What is the process for an Angular Component to receive a return object from a service following an HTTP

I am currently working with angular 4. Is there a way to retrieve an object from a service in this framework? export class LoginRequest { username : string; password : string; } export class LoginResponse { token : string; message : string; sta ...

Altering a public variable of a component from a sibling component

Within my application, I have two sibling components that are being set from the app.component: <my-a></my-a> <my-b></my-b> The visibility of <my-a> is determined by a public variable in its component: @Component({ module ...

The importance of handling undefined values in TypeScript and React

There is a condition under which the IconButton element is displayed: {value.content && <IconButton aria-label="copy" onClick={() => copyContent(value.content)}> <ContentCopy /> </IconButton> } However, a ...

Disabling breakpoints without bounds during TypeScript debugging in Visual Studio Code

While working on my Ubuntu machine using VS Code to debug a Nest.js TypeScript project, I am encountering issues with unbound breakpoints that are not being hit. Despite making various changes in the launch.json and tsconfig.json files, as well as trying o ...

Solve the error "Property 'container' of null is not accessible" in musickit.js while running an Angular application on a server

I am currently developing an application that combines Angular and MusicKit to offer users the ability to listen to music simultaneously. However, I encountered a challenging error when trying to run the application using ng serve --host x.x.x.x instead of ...

Can you explain the process of creating a join query in mongoDB?

How can I replicate this MySQL query using mongoDB and perform a join operation? I am encountering difficulties in translating it to work with mySQL. SELECT t.uid, count(j.job_id) AS x FROM verify AS t LEFT JOIN jobs AS j ON t.uid = j.job_id ...

Configuring TypeScript to utilize worker_threads

Currently, I am attempting to implement WebWorkers in my Typescript project and I have encountered a hurdle. Despite having installed @types/node and updating everything, 'worker_threads' has transitioned from an experimental feature to a stable ...

``There seems to be an issue with the functionality of Passport.js' multiple login system

I'm encountering a strange issue with my login system. Everything seems to be working fine, including local login, Google login, and Facebook login. However, the problem arises when I attempt to register with Google after already registering with Face ...

Nock does not capture the requests - Error: Failed to resolve address ENOTFOUND

Let me provide an overview of the structure in place. Jest is utilized for executing the testing process. Within my jest.config.json file, I incorporate the following line: "globalSetup": "<rootDir>/__tests__/setup.js", Inside setup.js, you will ...

What kind of function possesses additional attributes or characteristics?

I am finding it difficult to define the type for the function foo as demonstrated below: function foo() { do something } foo.boo = () => { do something else } foo("hello"); foo.boo("hello"); This JavaScript code is functioning corr ...

Guide on implementing the PUT method in Vue.js and NodeJS

Hey there, I'm facing an issue regarding updating a username using a text field. Below are the steps I took: I started by creating a model called user.js, followed by a UserController.js and then route.js. However, I'm stuck on how to actually ...

What is the importance of adding the ".js" extension when importing a custom module in Typescript?

This is a basic test involving async/await, where I have created a module with a simple class to handle delays mymodule.ts: export class foo { public async delay(t: number) { console.log("returning promise"); ...

JavaScript - Imported function yields varied outcome from module

I have a utility function in my codebase that helps parse URL query parameters, and it is located within my `utils` package. Here is the code snippet for the function: export function urlQueryParamParser(params: URLSearchParams) { const output:any = {}; ...

What is the best way to include additional fields within an array of objects in a mongoose schema, where these objects reference another mongoose schema?

I have a user mongoose schema with the field 'viewed_posts', which is an array of objects referencing another mongoose schema (post). Now, I need to add two more fields inside these objects. This was my attempt: viewed_posts: [ { hits: ...

Surprising Media Component Found in URL Parameters within the design

Exploring the page structure of my Next.js project: events/[eventId] Within the events directory, I have a layout that is shared between both the main events page and the individual event pages(events/[eventId]). The layout includes a simple video backgro ...

Choose a specific interface in Typescript

I am interested in developing a React alert component that can be customized with different message colors based on a specific prop. For example, I envision the component as <alert id="component" info/> or <alert id="component" ...

Utilizing a Link element in conjunction with ListItem and Typescript for enhanced functionality

I am currently using material-ui version 3.5.1 My goal is to have ListItem utilize the Link component in the following manner: <ListItem component={Link} to="/some/path"> <ListItemText primary="Text" /> </ListItem> However, when I tr ...