How to access Mongoose Ref _ids

Viewed 10

If we have a Mongoose model like

@index({ createdAt: 1 })
export class MyModel {
  readonly _id: mongoose.Types.ObjectId;

  @prop({ ref: () => UserModel, index: true })
  owner: Ref<IUserModel>;
}

We can do things like

const thing = await MyModel.findById(id).populate({path: 'owner', model: UserModel})

But it doesn't seem like we can just access owner without the populate

const thing = await MyModel.findById(id);
// Why is this possibly undefined? 
thing.owner; // Ref<IUserModel, mongoose.Types.ObjectId | undefined>

Because it is possibly undefined even though it definitely is not.

How can I access the actual ObjectId value that is stored in the db (thing.owner)?

0 Answers
Related