What is the best approach to defining document interfaces with Typescript and Mongodb?

Imagine a straightforward user database setup:

// db.ts
export interface User {
      _id: mongodb.ObjectId;
      username: string;
      password: string;
      somethingElse: string;
}

// user.ts
import {User} from "../db"
router.get("/:id", async (req, res) => {
    const id = req.params.id;
    // user._id is a mongodb.Object.
    const user: User = await db.getUser(id);

    res.send(user);
});

// index.ts
// code that will runs on browser
import {User} from "../../db"
$.get('/user/...').done((user: User) => {
    // user._id is string.
    console.log(user._id);
});

Everything functions smoothly until attempting to utilize this structure in client-side scripts. This occurs because the _id of the user converts to a hex string when sent as JSON from the server. When changing _id to mongodb.ObjectId | string, the behavior becomes strange. https://i.sstatic.net/FmNmW.png

Answer №1

To efficiently organize the data, consider the following approach:

interface User {
   username: string;
   password: string;
   somethingElse: string;
}

export interface UserJSON extends User {
   _id : string
}

export interface UserDB extends User {
   _id : mongodb.ObjectId
}

Subsequently, you can choose either UserJSON (for client-side) or UserDB (for server-side).

Answer №2

Shoutout to @drinchev for the helpful tip! I've come up with a more efficient solution by leveraging generics:

interface Member<IDType> {
    _id: IDType;
    name: string;
    messages: Message<IDType>[];
}

interface Message<IDType> {
    _id: IDType;
    content: string;
}

export type Database = Member<mongodb.ObjectID>;

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

Unveiling the Ultimate Method to Package Angular 2 Application using SystemJS and SystemJS-Builder

I'm currently in the process of developing an application and I am faced with a challenge of optimizing the performance of Angular 2 by improving the loading speed of all the scripts. However, I have encountered an error that is hindering my progress: ...

Trying to automatically select a checkbox upon page load in Angular 6

When the page loads, I want to automatically check a checkbox. Here is my component: var user = ViewprojectComponent.featuresList1; this.rules_id = user[0]; for(let i = 0; i <= this.rules_id.length; i++) { var checkedOn1 = this.rules_id[i]; this.Ru ...

Guide for converting a JavaScript function with spread arguments of different types to C# style

I am having difficulty with the strict typing in C# when it comes to function arguments. For my Reverse Polish Notation (RPN) calculator, the required arguments will be passed through a function call using a comma-separated list of different types: this.F ...

Narrow down product selection by multiple categories

I'm currently in the process of working with Express and MongoDB, where I have data items structured like the following: { "_id": { "$oid": "63107332e573393f34cb4fc6" }, "title": "Eiffel tower&quo ...

Using MongoDB Object as middleware in Express applications

I’m facing issues trying to access the "DB" database object that gets created when the MongoDB client module establishes a connection with my MongoDB database. Currently, I am encountering an error indicating that in data.js, 'db' is not defin ...

The specified 'contactId' property cannot be found within the data type of 'any[]'

I am attempting to filter an array of objects named 'notes'. However, when I attempt this, I encounter the following error: Property 'contactId' does not exist on type 'any[]'. notes: Array < any > [] = []; currentNot ...

Converting a string to Time format using JavaScript

I am working with a time format of 2h 34m 22s which I need to parse as 02:34:22. Currently, I am achieving this using the following code: const splitterArray = '2h 34m 22s'.split(' '); let h = '00', m = '00', s = &a ...

Is VSCode disregarding tsconfig.json and compiling individual files, causing misleading error messages to appear?

After updating typescript, angular, and all the libraries in my project, I encountered a new issue that was not present before. Although I successfully ensured that my code builds without any errors or warnings from the command line, Visual Studio Code sta ...

Prisma causing a compiler error

Currently, I am in the process of developing a project that integrates a GraphQL server and utilizes Prisma to establish a connection with the database. Additionally, I have chosen to implement this project using TypeScript. Unfortunately, as I compile my ...

Enhance the appearance of a custom checkbox component in Angular

I developed a customized toggle switch for my application and integrated it into various sections. Recently, I decided to rework it as a component. However, I am encountering an issue where the toggle switch button does not update in the view (it remains t ...

Having trouble implementing pagination while also sorting by a specific field in MongoDB

I need to query a collection with pagination and sorting by the dateCreated field in descending order to retrieve the latest documents. To optimize performance, I am keeping track of the lastKnownCommentId (Object id). Using the lastKnownCommentId helps pr ...

How to generate a new array in Angular by combining elements from two existing arrays for common items

I am currently working on a TypeScript function to compare two arrays and generate a third array containing the common items. For example: employees: any; offices: any; constructor() { this.employees = [ { fname: "John", lname: "James", sta ...

Registering a function for chart.js plugins that manipulates external data

Is there a way to pass external data to the chart.plugins.register function? I'm struggling because I can't access the necessary context: Chart.plugins.register( { beforeDraw: function (chart) { //implementation } }); I attempted using ...

Tips for adjusting card content to fit its size in material ui?

I'm looking to implement Material UI cards in a grid layout, each containing a Highcharts chart as shown in this demo. However, I'm facing an issue where the content does not adjust properly when the card size is fixed. How can I resolve this? A ...

There are a pair of Ionic2 menus; one is currently visible while the other remains hidden

I am having an issue with my Ionic2 app where I have two pages, each with similar menus named XXX.html. One page displays its menu correctly, but the other does not show its menu at all. Is there a limitation in Ionic2 that prevents having two menus on the ...

Is it possible to create a TypeScript type that matches the structure of a prop?

I have a list of different types: type A = 1 type B = 2 type X = 'x' type Y = 'y' An object will be received in the format Record<string, A | B>. For example: { test1: A, test2: B, test3: A}. The goal is to create a function that ...

The designated <input type=“text” maxlength=“4”> field must not include commas or periods when determining the character limit

In the input field, there are numbers and special characters like commas and dots. When calculating the maxLength of the field, I want to ignore special characters. I do not want to restrict special characters. The expected output should be: 1,234 (Total ...

What is the best way to utilize *ngSwitchWhen in a TypeScript environment?

I am currently working with Ionic2 and Angular2 and encountering an issue while trying to implement a segment using ngSwitchWhen. Unfortunately, the functionality is not working as expected and I am receiving an error message. How can I resolve this issue ...

Material-UI React Native components: Injecting Styles without Props

import {createStyles, WithStyles} from "@material-ui/core"; const styles = (theme: Theme) => createStyles({ root: {} }); interface MyProps extends WithStyles<typeof styles> { } export class MyComponent extends Component<MyProps ...

Determining the Size of Array Intersection using MongoDB's Aggregation Framework

In my Java web application, I am utilizing MongoDB's aggregation framework to create personalized recommendations for users by analyzing the preferences of other users. One of the key techniques I am employing involves examining array intersections. ...