I read the official documentation but still don't get it https://docs.mongodb.com/manual/tutorial/model-embedded-one-to-one-relationships-between-documents/ Explain me pls, how to create in my example. I have nest.js app with mongoose. Two schemas (2 tables in db):
1)
export type UserModelDocument = UserModel & Document;
@Schema()
export class UserModel {
@Prop()
email: string;
@Prop({ type: MongooseSchema.Types.ObjectId, ref: 'InviteModel' })
invite: InviteModel;
}
export const UserSchema = SchemaFactory.createForClass(UserModel);
@Schema()
export class InviteModel {
@Prop()
status: string;
}
export const InviteSchema = SchemaFactory.createForClass(InviteModel);
And here, in my service i create a user:
async create(createUserDto: CreateUserDto) {
const userExists = await this.userModel.findOne({ email: createUserDto.email });
if (userExists) {
this.logger.error('User already exists');
throw new NotAcceptableException('User already exists');
}
const createdUser = await new this.userModel(createUserDto).save();
//need some operations to save default invite too in the same user
return toCreateUserDto(createdUser);
}
How to add a relation one-to-one when registering for a new user, so that the object of the created user is also added invite object. Example:
{userEmail: "email@email.com",
invite: {
status: 'not_sent',
}
}
Сan i do it in one request? or I need to save in different requests?
const createdUser = await new this.userModel(createUserDto).save();
const createdInvite = await new this.inviteModel(createInviteDto).save(); ?