#error TS2322: Type 'ObjectId' is not assignable to type 'Territory | ObjectId | undefined'.

2 messages · Page 1 of 1 (latest)

mellow condor
#

I'm trying to write a seeder to test my database, and I'm getting the error in the title when trying to assign the _id of a newly created document to a mongoose.Schema.Types.ObjectId field. My code:

district.schema.ts:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { HydratedDocument } from 'mongoose';
import { Territory } from './territory.schema';

export type DistrictDocument = HydratedDocument<District>;

@Schema({
  autoIndex: true,
  timestamps: true,
})
export class District {
  @Prop({ required: true, unique: true, index: true })
  slug_name: string;

  @Prop()
  pretty_name: string;

  @Prop({
    default: null,
    required: false,
    index: true,
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Territory',
  })
  territory?: Territory;
}

export const DistrictSchema = SchemaFactory.createForClass(District);

territory.schema.ts:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { HydratedDocument } from 'mongoose';

export type TerritoryDocument = HydratedDocument<Territory>;

//@TODO Change name to territory
@Schema({
  autoIndex: true,
  timestamps: true,
})
export class Territory {
  @Prop({ required: true, unique: true, index: true })
  slug_name: string;

  @Prop()
  pretty_name: string;

  @Prop()
  abbreviation: string;
}

export const TerritorySchema = SchemaFactory.createForClass(Territory);
#

creating the fake district:

  createFakeDistrict(): District {
    const slug_name = faker.lorem.slug();
    const pretty_name = slug_name.split('-').join(' ');
    return {
      slug_name: slug_name,
      pretty_name: pretty_name,
      territory: undefined,
    };
  }

The actual assignment:

      const district = this.createFakeDistrict();
      const territory = this.createFakeTerritory();

      const createdTerritory = new this.territoryModel(territory);
      createdTerritory.save();
      district.territory = createdTerritory._id;
      const createdDistrict = new this.districtModel(district);
      createdDistrict.save();