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?
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?
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
So basically, what you define in mongoose schema only for mongoose to understand and type script doesn't care about it. If you populate
followingwhen retrieve record your interface will befollowing: User[], if not it will be an array of stringstring[]