Home > database >  Interface type for model mongoose with typescript
Interface type for model mongoose with typescript

Time:03-18

I have 2 models

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)

When I find Resource then populate type, I can't access type.name

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

VSCode show Error

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

How can I fix that?

CodePudding user response:

I found it

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