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

Can we modify a document in the callback function once a new document has been saved in a different collection?

After saving the newPost document to the posts collection and attempting to update other documents in the tags collection within the then() function, I encountered an issue. For some reason, the change in the tags collection does not happen as expected, an ...

When upgrading from ng15 to ng16, beware of the error message stating that the type '(event: RouterEvent) => void' cannot be assigned to type '(value: Event_2) => void.'

section, I encountered issues with my Angular project after upgrading from ng15 to ng16. Specifically, errors are arising when trying to implement the code snippet below. Can anyone provide insights on what may be causing problems with the event argument ...

When the next() function of bcrypt.hash() is called, it does not activate the save method in mongoose

Attempting to hash a password using the .pre() hook: import * as bcrypt from 'bcrypt'; // "bcrypt": "^1.0.2" (<any>mongoose).Promise = require('bluebird'); const user_schema = new Schema({ email: { type: String, required: tru ...

Is there an issue with the Mongoose update where $set and $push are not properly updating

What is the correct way to update MongoDB using $set and $push commands? Here is the data that I have: [ { _id: 57682f69feaf405c51fdf144, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abdfced8dfded8ced99aebd ...

Can you explain the purpose of the curly braces found in a function's parameter definition?

I am currently working on an Angular 5 project and came across this intriguing Typescript code snippet. (method) CreateFlightComponent.handleSave({ currentValue, stepIndex }: { currentValue: Partial<Flight>; stepIndex: number; }): void Can ...

Creating and updating a TypeScript definition file for my React component library built with TypeScript

As I work on developing a React library using TypeScript, it is important to me that consumers of the library have access to a TypeScript definition file. How can I ensure that the TypeScript definition file always accurately reflects and matches the Java ...

What is the best way to dynamically disable choices in mat-select depending on the option chosen?

I was recently working on a project that involved using mat-select elements. In this project, I encountered a specific requirement where I needed to achieve the following two tasks: When the 'all' option is selected in either of the mat-select e ...

TypeScript focuses on checking the type of variables rather than their instance

Is there a way to pass a type (not an instance) as a parameter, with the condition that the type must be an extension of a specific base type? For example abstract class Shape { } class Circle extends Shape { } class Rectangle extends Shape { } class ...

At first, Typescript generics make an inference but are ultimately specified

In my TypeScript code, I have defined a custom Logger class with specific options. The DefaultLevel type is created as a union of 'info' and 'error'. The LoggerOptions interface includes two generics, CustomLevels and Level, where Custo ...

Enhancing Application Performance Through Next.js Development

I'm currently working on an application using next.js and I am looking to implement code splitting in order to reduce the bundle size and load pages on demand. Unfortunately, I have not been able to find a way to do this without specifying routes. Fo ...

Undefined output in Typescript recursion function

When working with the recursion function in TypeScript/JavaScript, I have encountered a tricky situation involving the 'this' context. Even though I attempted to use arrow functions to avoid context changes, I found that it still did not work as ...

Is there a way to prevent the URL of my Next.js app from constantly changing?

Our current Next.js project requires that the static URL remains constant, even when navigating between pages. This is a client requirement that we must adhere to. Can you provide suggestions on how we can achieve this? Maintaining the same URL throughout ...

Ensuring the accurate usage of key-value pairs in a returned object through type-checking

After generating a type definition for possible response bodies, I am looking to create a function that returns objects shaped as { code, body }, which are validated against the typing provided. My current solution looks like this: type Codes<Bodies> ...

Is it possible to automatically open the Tinymce Comments sidebar without the need for a manual button click?

After successfully implementing the Tinymce comments plugin into our configuration, we have come across a request from our users. They would like the 'showcomments' button to automatically trigger on page load, displaying the sidebar containing t ...

Issue with Angular 2 Custom Pipe not Refreshing Unless Object is Saved

I recently created a custom Angular 2 pipe that formats a phone number from a 10-digit string to 'XXX-XXX-XXXX'. The pipe is functioning perfectly, but the issue arises when it fails to update in real-time during keypress; instead, it updates onl ...

Searching through data fields in MongoDB that have been filled with information

In my Mongoose queries, I am dealing with models known as "Activities" that have a specific schema structure. This schema includes fields such as actor, recipient, timestamp, activity, event, and comment. var activitySchema = new mongoose.Schema({ act ...

Module lazily loaded fails to load in Internet Explorer 11

Encountering an issue in my Angular 7 application where two modules, txxxxx module and configuration module, are lazy loaded from the App Routing Module. The problem arises when attempting to navigate to the configuration module, as it throws an error stat ...

Node Application experiences compatibility issues with browsers but functions correctly with cURL

My NodeJS application is connected to MongoDB using the mongooseJS driver and hosted on AWS through OpsWorks with Monit monitoring. Everything runs smoothly after deployment, but after about an hour, attempting to access the application in a browser result ...

How can I swap a string for a symbol in JavaScript?

Is there a way to convert the text @abc some text here to <a href="some_url">@abc</a> some text here using JavaScript? Are there any libraries that can help with this task? ...

Add the arrivalDate value to the existing array

Is there a way to store each arrivalDate from the API's JSON response into my array list, even though the array is currently empty? Here is a snippet of the JSON returned by the API: { "reservations": { "reservationInfo&quo ...