@types/mongoose how to type ObjectIds with a ref

Viewed 1394

Using Typescript and mongoose, I wanted to be able to work with my custom model types. However, I haven't found an example of a model typing a property with a Schema.Types.ObjectId ref to another document. I'm trying to figure out how to do it and haven't been successful so far.

Here's what I would want my model interface to look like:

import { Document, Schema, model, Model } from 'mongoose'
import ObjectId = Schema.Types.ObjectId

export interface ITask extends Document {
  description: string
  isActive: boolean
  children: ObjectId[] | ITask[] // <-- any[] works but limits typing
}

export const UserSchema: Schema = new Schema({
  description: String,
  isActive: Boolean,
  children: [{
    type: ObjectId,
    ref: 'Tasks'
  }]
}, { collection: 'Tasks' })

export const Task: Model<ITask> = model<ITask>('Task', TaskSchema)

When I implement this model in my code, Typescript throws a type error no matter how I type the interface (except any, of course):

async createChildTask(ctx: Context, next) {

  const task = new Task(ctx.body)
  task = await task.save()
  const parent = await Task.findById(ctx.params.taskId)
  parent.children.push(task) // <-- "property description does not exist on type"
  ...
}

Mongoose handles ObjectId typings in code as either the string of their id or the fully populated object. I want to be able to expect both, but Typescript doesn't seem to like that with this specific instance.

0 Answers
Related