1. Home
  2. Docs
  3. Engineering
  4. Serverless Functions (Mid...
  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 {
  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') });

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *