Node mongoose typescript how to type { type: ObjectId, ref: 'User' }

772 views Asked by At

I'm use mongoose with typescript following this https://medium.com/@agentwhs/complete-guide-for-typescript-for-mongoose-for-node-js-8cc0a7e470c1

I don't know how to type

following: [{ type: ObjectId, ref: 'User' }],

Can you give me a hint, please?

2

There are 2 answers

0
Neoflies On BEST ANSWER

So basically, what you define in mongoose schema only for mongoose to understand and type script doesn't care about it. If you populate following when retrieve record your interface will be following: User[], if not it will be an array of string string[]

0
Felix Orinda On

When using defined types for mongoose and typescript you have to create an interface or type eg

import {Document} from "mongoose"

type UserType={
 username:String,
 _doc:any
 }&Document

//Or

interface IUser extends Document{
 username:String,
 _doc:any
 }

The _doc is used to get the body of the object body on query restructuring Say you have a Blog and has user who is the author how do we map that?

type BlogType={
    title:{
    type:String,
    required:true
 },
author:{
   type:ShemaTypes.ObjectId,
   ref:'User',
   required:true,
},
 comments:{
    type:[
{
    user:ShemaTypes.ObjectId,
    content:String,
}
  ]
}&Document

Using the ref makes it easy to query the other table as a join for the table in which the Object Id is referenced When working with arrays you just define the structure of data you want to store in the type property