lonix
lonix

Reputation: 20591

How to define mongoose _id in TypeScript interface?

I'm using Mongoose and TypeScript with the interface+class+schema approach.

What is the canonical way to store the _id field?

I know the db stores it as a bson ObjectID. But I've seen some examples using string and others using mongoose's ObjectId, and then converting between them for various reasons - so I'm unsure which to use.

interface Animal {
  _id: ?type?;        // ?
  name: string;
}

Is it advisable to use

Also, assuming it is correct to use objectid - I want to avoid taking a dependency on mongoose in the interface file. Is it safe/advisable to use the bson package's ObjectID instead - are they equivalent?

Upvotes: 24

Views: 30785

Answers (3)

hoangdv
hoangdv

Reputation: 16127

UPDATE: 4 years later and mongoose claims this approach will be dropped for performance reasons in it's next release. See docs link in comments.

You can extend your interface with mongoose.Document. Your interface will be come

interface Animal extends mongoose.Document { 
  name: string;
}

Usage:

export let AnimalSchema = mongoose.model<Animal>('animal', schema, 'animals');
let animal = await AnimalSchema.find({_id: "id"}).exec();
// animal._id / animal.name

Upvotes: 6

kadiro
kadiro

Reputation: 1116

you can do this

import { Types } from 'mongoose';
interface Animal {
  _id: Types.ObjectId,      
  name: string
}

Upvotes: 25

Sir hennihau
Sir hennihau

Reputation: 1774

Taken from the mongoose documentation:

  • Import Types from mongoose
  • Use this type for your _id
import { Types } from 'mongoose';

interface Animal {
  _id: Types.ObjectId;
  name: string;
}

Upvotes: 13

Related Questions