Model Mongoose TypeScript Interface Type

I am working with 2 models in my project

import {model, Schema, Types} from 'mongoose'
interface IResource  {
    user : Types.ObjectId | IUsers,
    type : Types.ObjectId | IResourceData,
    value : number,
    lastUpdate : number | Date,
    
const ResourceSchema = new Schema<IResource>({
    user : {type : Types.ObjectId, ref : 'users'},
    type : {type: Types.ObjectId , ref : 'resource_datas'},
    lastUpdate : {type : Date , default : Date.now},
    value : {type : Number, default : 500}
})

const Resources = model<IResource>('resources' , ResourceSchema)


interface IResourceData {
    name : string,
}
const ResourceDataSchema = new Schema<IResourceData>({
    name : {type : String},
})
const ResourceDatas = model<IResourceData>('resource_datas' , ResourceDataSchema)

However, when I try to find a Resource and populate its type, I encounter an issue accessing the type's name property

const userResource = await Resources.findOne({user : _id}).populate('type')
const resourceName = userResource.type.name //Error here

VSCode is displaying an error message that says:

Property 'name' does not exist on type 'ObjectId | IResourceData'.
  Property 'name' does not exist on type 'ObjectId'.

What steps should I take to resolve this problem?

Answer №1

I have discovered the solution

interface ITypeOfResource extends Types.ObjectId,IResourceData{} 
interface IResource  {
    user : Types.ObjectId | IUsers,
    type : ITypeOfResource 
    value : number,
    lastUpdate : number | Date,
}

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

Tips on converting Nextjs generated Prisma types case from snake_case to camelCase

I have a full-stack application built with Next.js and Prisma ORM "next": "12.3.0" "prisma": "^4.5.0" Essentially, I am looking to convert the case of my types from snake_case to camelCase to align with the front-en ...

Need help restarting a timer I've built in Angular with just a click?

I am in the process of developing a compact application that will help me keep track of my activities within a specific time frame. Once I input an activity into a field and click "OK," it should be added to a list. My current challenge lies in resetting ...

Is it possible for FormArray to return null?

Hello there. I've attempted various methods, but none of them seem to be effective. Currently, I am working on this task where I need to start a formArray for emails. email: [testestest] However, what I have is: email: [testestest] I'm encoun ...

Issues with getOptionLabel in Material UI

I have a constant with the following values : const Reference = [ { label: "RF-100", year: "Test" }, { label: "RF-200", year: "Test2" }, { label: "RF-300", year: "Test3" }, ]; and my Autoco ...

Access-Control-Allow-Methods does not allow the use of Method PUT in the preflight response, as stated by Firebase Cloud Functions

I am facing an issue with my Firebase cloud function endpoint. I have a setup where it forwards PUT requests to another API endpoint. I have configured the following Access-Control-Allow- headers: // src/middlewares/enableCORS.ts export default function en ...

Issue with NgFor nested component not refreshing after @Input modification

When populating a component called ContactUpdatableItem within a NgFor, the code looks like this: <section class="plContactCreation-listItem" *ngFor="let contact of contacts$ | async; index as idx" > <contact-updatable-item [c ...

Changing an Angular template.html into a PDF document within an Angular 2 application can be achieved by utilizing

Exploring Angular 2 and looking for a way to export my HTML component in Angular 2 to PDF using jspdf. I want to convert dynamically generated tabular HTML into a PDF using jspdf. Below is a snippet of sample code along with a Plunker link: import {Comp ...

When utilizing <number | null> or <number | undefined> within computed() or signals(), it may not function properly if the value is 0

I've encountered an issue while implementing signals and computed in my new Angular project. There's a computed value that holds an id, which is initially not set and will be assigned by user interaction. To handle this initial state, I attempte ...

Error: Conversion to Object ID unsuccessful for entity "XXX" in field "_id" within the "Product" model

const express = require('express'); const router = express.Router(); const asyncHandler = require('express-async-handler'); const Product = require('../models/productModel'); router.get('/', asyncHandler(async (req, ...

Steps for modifying the value of a field within an Angular formGroup

Is there a way to update the value of the "send_diagnostic_data" field in a separate function? private generateForm(): void { this.messageForm = new FormGroup({ message: new FormControl(''), date: new FormControl(new Date()), messag ...

Using formControlName with an Ionic2 checkbox allows for seamless integration of

Currently facing an obstacle with checkboxes in ionic2. Here is how I am using the checkbox: <ion-item> <ion-label>Agree</ion-label> <ion-checkbox color="dark" id="agree" name='agree' class="form-control" formContro ...

Adding a new object to a nested array with MongoDB and Node.js

I'm struggling with pushing an object to a nested array, specifically in this Board document: { "boardMembers": [ "5f636a5c0d6fa84be48cc19d" ], "boardLists": [ { "cards": ...

Encountered an issue with valid types while executing the following build

Encountering an error when attempting to run the next build process. https://i.stack.imgur.com/qM3Nm.png Tried various solutions including updating to ES6, switching the module to commonJs, downgrading webpack to version 4 with no success. The only worka ...

Exploring the Realm of Javacript Template Literal Capabilities

Is it possible to define a variable inside a template literal and then utilize it within the same template? If this isn't feasible, it appears to be a significant feature that is lacking. const sample = tag` some random words, ${let myvar = 55} addit ...

Showing data in a manner that only includes the information from the mongoose database that is needed

Can we show information from a collection where the population field is matching role: '4edd40c86762e0fb12000002'? recommendModel.find({ userId: userId }) .populate('recommendedBy',{role: '4edd40c86762e0fb1 ...

What is the best way to send serverside parameters from ASP.Core to React?

After setting up a React/Typescript project using dotnet new "ASP.NET Core with React.js", I encountered the following setup in my index.cshtml: <div id="react-app"></div> @section scripts { <script src="~/dist/main.js" asp-append-versi ...

Transfer all specified resources from one stack to another in AWS CDK

In the process of creating two stacks, I aim to reference the resources from the first stack, such as Lambda, API Gateway, and DynamoDB, in the second stack without hard coding all the resources using Stack Props. Please note: I do not want to use Stack Pr ...

Mapping a TypeScript tuple into a new tuple by leveraging Array.map

I attempted to transform a TypeScript tuple into another tuple using Array.map in the following manner: const tuple1: [number, number, number] = [1, 2, 3]; const tuple2: [number, number, number] = tuple1.map(x => x * 2); console.log(tuple2); TypeScript ...

Utilizing AWS Websockets with lambda triggers to bypass incoming messages and instead resend the most recent message received

I am facing an issue when invoking a lambda that sends data to clients through the websocket API. Instead of sending the actual message or payload, it only sends the last received message. For example: Lambda 1 triggers Lambda 2 with the payload "test1" ...

Invoke the method in customButton component of fullcalendar

I've integrated a custom button into my fullcalendar: ngOnInit() { this.calendarOptions = { customButtons: { custom1: { text: 'Add event', click() { this.openModal(); } } }, height: 600, editable: t ...