我阅读了官方文档,但仍然不明白https://docs.mongodb.com/manual/tutorial/model-embedded-one-to-one-relationships- Between-documents/ Between-documents/ \n请解释一下,如何在我的示例中创建。\n我有带有猫鼬的 Nest.js 应用程序。\n两个架构(数据库中的 2 个表):
\n1)
\nexport type UserModelDocument = UserModel & Document;\n\n@Schema()\nexport class UserModel {\n @Prop()\n email: string;\n\n @Prop({ type: MongooseSchema.Types.ObjectId, ref: \'InviteModel\' })\n invite: InviteModel;\n}\n\nexport const UserSchema = SchemaFactory.createForClass(UserModel);\nRun Code Online (Sandbox Code Playgroud)\n@Schema()\nexport class InviteModel {\n\n @Prop()\n status: string;\n}\n\nexport const InviteSchema = SchemaFactory.createForClass(InviteModel);\nRun Code Online (Sandbox Code Playgroud)\n在这里,在我的服务中我创建了一个用户:
\nasync create(createUserDto: CreateUserDto) {\n const userExists = await this.userModel.findOne({ email: createUserDto.email });\n if (userExists) {\n this.logger.error(\'User already exists\');\n throw new NotAcceptableException(\'User already exists\');\n }\n const createdUser = await new this.userModel(createUserDto).save();\n//need some operations to save default invite too in the same user\n return toCreateUserDto(createdUser);\n }\nRun Code Online (Sandbox Code Playgroud)\n如何在注册新用户时添加一对一的关系,以便创建的用户的对象也添加邀请对象。\n示例:
\n{userEmail: "email@email.com",\n invite: {\n status: \'not_sent\',\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\xd0\xa1an 我在一个请求中完成它吗?或者我需要保存在不同的请求中?
\nconst createdUser = await new this.userModel(createUserDto).save();\nconst createdInvite = await new this.inviteModel(createInviteDto).save(); ?\nRun Code Online (Sandbox Code Playgroud)\n
文档中对此进行了很好的解释,如果您有不那么频繁搜索的数据,您可以将其卸载到第二个集合,以减少主文档的大小并提高读取性能,如果您需要不那么频繁的数据,您将向其发出第二个请求第二个集合。一般来说,如果第一个集合中的文档不是很大并且对读取性能没有影响,最好是将字段嵌入第一个集合中,并避免太多集合并在单个调用中获取所有内容。
集合1:
{ _id:"useremail" , frequentData: "the data1" }
Run Code Online (Sandbox Code Playgroud)
集合2:
{ _id:"useremail" , lessFrequentData:"the data2" }
Run Code Online (Sandbox Code Playgroud)
集合1:
{ _id:"usermail" , frequentData: "the Data1" , lessFrequentData:"the Data2" }
Run Code Online (Sandbox Code Playgroud)
PS我个人的观察:mongoDBwiredTiger存储引擎将数据分割并存储到存储上的32KB块中,因此低于该大小的文档被认为相对较小,如果没有其他特定要求,嵌入似乎是最好的选择......文档大小很重要但在文档模型设计中首选的是非规范化数据,正确的索引创建和利用对性能的提升更有帮助。
| 归档时间: |
|
| 查看次数: |
1076 次 |
| 最近记录: |