How to define mongoose _id in TypeScript interface?
12,618
Solution 1
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
Solution 2
you can do this
import { ObjectId } from 'mongoose';
interface Animal {
_id: ObjectId
name: string
}
Related videos on Youtube
Author by
lonix
Updated on September 23, 2022Comments
-
lonix over 1 year
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 usingstring
and others using mongoose'sObjectId
, 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
string
mongoose.Types.ObjectId
mongodb.ObjectID
bson.ObjectID
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'sObjectID
instead - are they equivalent? -
lonix about 5 yearsI do it another way to keep my entity files clean of infrastructure dependencies. Also, what about the original issue - what type is best to use?
-
hoangdv about 5 yearsaww, I think
mongoose.Types.ObjectId
is good for you case,mongoose.Types.ObjectId
has been defined bytypeof mongodb.ObjectID & { (s?: string | number): mongodb.ObjectID; };