Engineering

  1. Home
  2. Docs
  3. Engineering
  4. Serverless Functions (Middy)
  5. MongoDB Client Library (Typegoose/Mongoose)

MongoDB Client Library (Typegoose/Mongoose)

Common Mistake: Using ObjectId Type

Using the type ObjectId can be done by defining it as follows:

import * as mongoose from 'mongoose';
import { prop } from '@typegoose/typegoose';

class FooModel {
  @prop()
  userId: mongoose.Types.ObjectId;
}

You need to refer to the full length type since defining it as type ObjectId = mongoose.Types.ObjectId and referencing that will lead to it being an Object at compile time, meaning Typegoose will translate the property type to Mixed.

In order to query this model later you should use the type mongoose.Types.ObjectId.

const FooModel = getModelForClass(FooModel);
FooModel.findOne({ userId: new mongoose.Types.ObjectId('5e997f95d6a35f3a0def3339') });
Was this article helpful to you? Yes No

How can we help?

Leave a Reply

Your email address will not be published.