typegoose: Property '_id' does not exist on type 'ObjectId'

Property ‘_id’ does not exist on type ‘ObjectId’

Mongoose adds a _id getter to ObjectId instances so you can use story.author._id regardless of whether author is populated.

Why do you want it

I can always use document._maybePopulated._id to get the ObjectID in Javascript. However, typescript refuses to compile with this error.

Screenshot_20200408_134301

mongoose lets you disable this getter, but it is added by default.

This is partially an issue with the @types/mongoose, in that the typing are out of date and do not provide the correct interface:

    /*
      * section types/objectid.js
      * http://mongoosejs.com/docs/api.html#types-objectid-js
      */
    var ObjectId: ObjectIdConstructor;

    // mongodb.ObjectID does not allow mongoose.Types.ObjectId(id). This is
    //   commonly used in mongoose and is found in an example in the docs:
    //   http://mongoosejs.com/docs/api.html#aggregate_Aggregate
    // constructor exposes static methods of mongodb.ObjectID and ObjectId(id)
    type ObjectIdConstructor = typeof mongodb.ObjectID & {
      (s?: string | number): mongodb.ObjectID;
    };

    // var objectId: mongoose.Types.ObjectId should reference mongodb.ObjectID not
    //   the ObjectIdConstructor, so we add the interface below
    interface ObjectId extends mongodb.ObjectID { 
      // _id: mongodb.ObjectId; // should be here as of mongoose 5.8
    }

However, this is also an issue with the Ref definition:

/**
 * Reference another Model
 * @public
 */
export declare type Ref<R, T extends RefType = R extends {
    _id: RefType;
} ? R['_id'] : mongoose.Types.ObjectId> = R | T;

By adding _id: bson:ObjectId to the mongoose ObjectId definition, the error becomes property _id does not exist on type MySchema, where MySchema is the name of a class being referred to in Ref<MySchema>.

I would have a local definition for Ref<T> which supported this, but honestly my Typings-foo isn’t good enough to pick apart the current declaration for Ref

Example

index.ts

import { prop, Ref, getModelForClass  } from '@typegoose/typegoose'
class Friend {
    @prop()
    name: string;
}

class User {
    @prop()
    name: string;

    @prop({ref: Friend})
    _friend: Ref<Friend>;
}

const FriendModel = getModelForClass(Friend);
const UserModel = getModelForClass(User);

UserModel.findOne().populate('_friend').then(user => {
    const friendId = user._friend._id;
});

tsconfig.json*

{
    "compilerOptions": {
      "outDir": "dist",
      "inlineSourceMap": true,
      "experimentalDecorators": true,
      "emitDecoratorMetadata": true
    },
    "include": ["index.ts"]
  }

package.json

{
  "name": "typegoose-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "tsc -p ."
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@typegoose/typegoose": "^6.4.0",
    "@types/mongoose": "^5.7.9",
    "mongoose": "^5.9.7",
    "typescript": "^3.8.3"
  }
}

result

$ npm run build

> typegoose-example@1.0.0 build /home/matt/Projects/Tests/Typegoose
> tsc -p .

index.ts:19:35 - error TS2339: Property '_id' does not exist on type 'Ref<Friend, ObjectId>'.
  Property '_id' does not exist on type 'ObjectId'.

19     const friendId = user._friend._id;
                                     ~~~


Found 1 error.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 16 (6 by maintainers)

Most upvoted comments

  const obj = await this.refreshTokenModel
      .findOne({ token })
      .populate('userId')
      .orFail(() => new BadRequestException('Invalid Token'))

    if (!isDocument(obj.userId)) throw new BadRequestException('unable to fetch user details');

    return {
      access_token: this.generateAccessToken(obj.userId.toObject())
    }        

thanks a lot solution worked for me

import { prop, getName, getModelForClass, Ref, isDocument } from '@typegoose/typegoose';
import { Types } from 'mongoose';

type MyRef<T> = Ref<T & { _id: Types.ObjectId }, Types.ObjectId & { _id: Types.ObjectId }>

export class FirstClass {
    @prop()
    myproperty!: string;
}

export const First = getModelForClass(FirstClass)

export class SecondClass {
    @prop({ ref: getName(FirstClass) })
    first!: MyRef<FirstClass>;
}

export const Second = getModelForClass(SecondClass)

async function run() {

    const second = await Second.findOne().populate("first").exec();
    if (!isDocument(second)) {
        throw new Error("no doc");
    }

    const id1 = second.first._id; // Typescript doesn't complain

    if (!isDocument(second.first)) {
        throw new Error("no doc");
    }
    const id2 = second.first._id; // Typescript doesn't complain
    const myproperty = second.first.myproperty; // Typescript doesn't complain
}

run()

I found a solution that doesn’t require to specify the id in the model.

Its solution is already there in the docs

import { getModelForClass, prop} from "@typegoose/typegoose";
import type { ObjectId } from "mongoose";

export class User {
public _id!:  ObjectId; // do not use prop if you dont want to overwrite defaults
}

export const AdminModel = getModelForClass(Admin);

You are attempting to reference the interface, not the the resulting document interface / mode.

Try typing the both and employing the resulting iDocument, at the model creation stage:

type iDocument = IUsers & Document
export interface IUsersDocument extends iDocument {}

const User:IUsersDocument;

…the _id reference is now typed…!

I made it works by adding a custom RefType which wraps Ref. Could we implement a similar solution to Typegoose’s library?

code_preview