I haven't found this part of NestJS to be flexible enough. A working solution (tested) for me is the following:
@Schema({_id: false}) // _id:false is optional
class Name {
@Prop() // any options will be evaluated
firstName: string; // data type will be checked
@Prop()
lastName: string;
}
@Schema()
class User {
@Prop({type: Name}) // {type: Name} can be omitted
name: Name;
}
Defining your schemas this way will keep everything (class decorators, passed options, data types verification, NestJS functionalities, etc.) working as expected. The only "issue" is that _id
properties will be created for each @Schema
and you might not want that, like in your case. You can avoid that by adding {_id: false}
as an options object to your @Schema()
. Keep in mind, that any further nested schemas won't be prevented from creating _id
properties, e.g.
This:
@Schema() // will create _id filed
class Father {
age: number;
name: string;
}
@Schema({_id: false}) // won't create _id field
class Parents {
@Prop()
father: Father;
@Prop()
mother: string;
}
@Schema()
class Person {
@Prop()
parents: Parents;
}
will produce this:
{
_id: ObjectId('someIdThatMongoGenerated'),
parents: {
father: {
_id: ObjectId('someIdThatMongoGenerated'),
age: 40,
name: Jon Doe
},
mother: Jane Doe
}
}
The other workaround is to use native mongoose for creating your schemas in NestJS, like so:
const UserSchema = new mongoose.Schema({
name: {
firstName: {
type: String, // note uppercase
required: true // optional
},
lastName: {
type: String,
required: true
}
}
});