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

"Utilizing mongoose to perform a full join on arrays within MongoDB

I am trying to perform a 'join' on two collections. The first one is referred to as parent. The second one is known as child. This is the structure of the parent object: { "_id": "id_123" "name": " ...

What is the best way to create a custom hook that updates in response to changes in state?

My situation involves a custom hook that handles a specific state variable. After making changes to the state, it doesn't update right away. To solve this issue, I need to subscribe to it using useEffect. The challenge is that I can't directly ...

The Angular 4 application is unable to proceed with the request due to lack of authorization

Hello, I am encountering an issue specifically when making a post request rather than a get request. The authorization for this particular request has been denied. Interestingly, this function works perfectly fine with my WPF APP and even on Postman. B ...

tsconfig is overlooking the specified "paths" in my Vue project configuration

Despite seeing this issue multiple times, I am facing a problem with my "paths" object not working as expected. Originally, it was set up like this: "paths": { "@/*": ["src/*"] }, I made updates to it and now it looks like ...

Efficient management of pre-built assets in Vite

I am currently developing a Vue application using Vite. Within the content folder, I have numerous files (ranging from 10 to 100) located as follows: content/block/paragraph.json content/block/theorem.json content/inliner/link.json ... My goal is to creat ...

Is it possible to nullify an object and utilize nullish coalescing for handling potentially undefined constants?

In my development work with React, I often utilize a props object structured like this: const props: { id: number, name?: string} = { id: 1 }; // 'name' property not defined const { id, name } = props; // the 'name' constant is now fore ...

Problem with sorting when using $in operator in MongoDB

I am looking to retrieve documents from a MongoDB collection where the IDs match those in an array: [ '5f80a44d0179262f7c2e6a42', '5f8c00762fae890e9c4d029c', '5f802cf8abac1116a46bf9d4' ] The problem arises when the docu ...

Search for a property within a JSON object field using Mongoose

Suppose I have a schema like this: var TempSchema = new Schema({ location: Schema.Types.Mixed }); The 'location' field will store a JSON object. Now, if I want to search by a property within this JSON object field, can I use the following ...

Is there a way to connect a Mongo-Docker Container with a basic CRUD Server Container built with Nodejs on a bridge network?

In my setup, I have a bridge network named my_network, a Mongo container, and a CRUD server running on Node.js. I start the MongoDB container using the following command: docker run -dit --name my_server --network web_server -p 27023:27017 --rm mongo To l ...

The Typescript decorator is unable to access the property type within its own scope

I am currently in the process of developing a dependency injector for use in my VUE js project. Recently, I created an Inject decorator with the intention of accessing a property type. It was functioning perfectly fine yesterday, but now it seems that som ...

"Querying with Mongoose's findOne Method Yields Empty Object Result

I have successfully saved some documents in mongodb compass and now I am attempting to retrieve the values by querying certain parameters. As I understand it, when using mongodb findOne, there are arguments such as query, fields(by default value: all), o ...

When utilizing regex in my mongoDb search query, I am getting back an empty list

I'm currently facing an issue with searching for users by name in my database. For example, if I have user first names like Alan, Alex, Arun, Alexender, Bob, and Bill. When I run the following query: router.get('/friendSearch/:q', function ...

Disregard any unnecessary lines when it comes to linting and formatting in VSC using EsLint and Prettier

some.JS.Code; //ignore this line from linting etc. ##Software will do some stuff here, but for JS it's an Error## hereGoesJs(); Is there a way to prevent a specific line from being considered during linting and formatting in Visual Studio Code? I h ...

What is the best way to implement an onChange handler for React-Select using TypeScript?

I am struggling to properly type the onchange function. I have created a handler function, but TypeScript keeps flagging a type mismatch issue. Here is my function: private handleChange(options: Array<{label: string, value: number}>) { } Typescrip ...

Manually load an instance of the Mongoose model yourself

Is there a way to create a model instance from an object and notify Mongoose that it already exists? I'm getting data from the cache, so it's always current. I attempted to accomplish this using var instance = new SomeModel({ '_id': & ...

What causes the error "property does not exist on type" when using object destructuring?

Why am I encountering an error in TypeScript when using Object destructuring? The JavaScript code executes without any issues, but TypeScript is showing errors. fn error: This expression is not callable. Not all elements of type '(() => void) | ...

Outdated Information Found in Meteor Collection

Previously, I had code that successfully made a HTTP get call from the server, utilized EJSON.parse to parse data retrieved from a JSON-formatted URL, and then added information from the parsed data to a Meteor collection. However, after updating to Meteor ...

What is the best way to simulate a constructor-created class instance in jest?

Suppose there is a class called Person which creates an instance of another class named Logger. How can we ensure that the method of Logger is being called when an instance of Person is created, as shown in the example below? // Logger.ts export default cl ...

Can you explain the significance of the 'project' within the parserOptions in the .eslintrc.js file?

Initially, I struggle with speaking English. Apologies for the inconvenience :( Currently, I am using ESLint in Visual Studio Code and delving into studying Nest.js. I find it difficult to grasp the 'project' setting within the parserOptions sec ...

Methods to close the currently active ngx-modal when a new modal is triggered within the same Angular 8 component

I am currently working on developing a versatile modal component that has the ability to be called from within the same modal itself. Is there any way to configure the component and modal in such a manner that when the reusable component is triggered, it ...