Reputation: 1109
I know it seems quite basic, but I can't seem to find the correct way of setting up the _id field in the Nest.js mongoose schema. I've attached an image, and was just wondering what the best way to set this property? I get the following error
'SchemaType' only refers to a type, but is being used as a namespace here.ts(2702)
Upvotes: 2
Views: 13845
Reputation: 1283
A little late to the party and I'm not strictly answering the question, but this might still be helpful for some. This is in response to Tornike Menabde's comment.
You can use the HydratedDocument
type from the mongoose package to access the properties, that are being added automatically by mongoose or mongo, i.e. _id
.
import { HydratedDocument } from 'mongoose';
export type UserDocument = HydratedDocument<User>;
@Schema()
export class User {
// no _id required here
}
The type UserDocument looks like this: type UserDocument = Document<unknown, {}, User> & User & { _id: Types.ObjectId; }
, so it already includes the '_id' property.
Upvotes: 3
Reputation: 1855
You don't need to define _id
as a prop because it already exists in the Document
class. Queries performed against your MusicSupervisorModel
will return an object of MusicSupervisorDocument
. In case you want to add a field of ObjectId
type to your schema you have to do it as follows to preserve casting to ObjectId
:
import { Document, SchemaTypes, Types } from 'mongoose';
...
@Prop({ type: SchemaTypes.ObjectId })
yourField: Types.ObjectId
Upvotes: 6
Reputation: 3476
When defining your Mongoose schema in NestJS you really don't have to specify the _id field and all will be fine.
If you want to explicitly define it you have to use following:
...
_id: Schema.Types.ObjectId
...
Upvotes: 2