如何在一个命令中使用 mongoose 检索配置文件和用户模式?

Posted

技术标签:

【中文标题】如何在一个命令中使用 mongoose 检索配置文件和用户模式?【英文标题】:How to retrive profile and user schema with mongoose in one command? 【发布时间】:2020-01-23 15:05:45 【问题描述】:

如何将用户和个人资料放在一起?

User 架构是这样定义的:

const UserSchema = new Schema(
  email:  type: String, required: true ,
  name:  type: String, required: true ,
  password:  type: String ,
  picture:  type: String ,
);

和配置文件架构:

const ProfileSchema = new Schema(
  user:  type: Schema.Types.ObjectId, ref: 'User' ,
  setting1:  type: String, enum: ['YES', 'NO', 'UNKNOWN'], default: 'UNKNOWN' ,
  setting2:  type: String, enum: ['YES', 'NO', 'UNKNOWN'], default: 'UNKNOWN' ,
  setting3:  type: String, enum: ['YES', 'NO', 'UNKNOWN'], default: 'UNKNOWN' ,
);

当我询问用户时,如何在一个命令行/行中检索profile

User.findOne( email: 'blabla@gmail.com' )

我已经尝试填充但它不起作用:

User.findOne( email: 'blabla@gmail.com' ).populate('profile')
请注意:我不想在同一架构中的用户中拥有个人资料。

【问题讨论】:

【参考方案1】:

您需要在 UserSchema 中链接配置文件:

const UserSchema = new Schema(
  profile:  type: Schema.Types.ObjectId, ref: 'Profile' ,
  email:  type: String, required: true ,
  name:  type: String, required: true ,
  password:  type: String ,
  picture:  type: String ,
);

【讨论】:

有不需要改变用户架构的解决方案? 您正在寻找尚不可用的反向填充功能。在这里找到可能的解决方案:***.com/questions/37691476/… 一般来说,最简洁的解决方案是按照建议构建架构并直接填充所需的数据。

以上是关于如何在一个命令中使用 mongoose 检索配置文件和用户模式?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 mongoose ORM 存储/检索到 mongodb

如何在 Mongoose 的嵌入式文档中检索数组的最后一个对象?

如何在 Mongoose 的嵌入式文档中检索数组的最后一个对象?

如何在 Mongoose 中更改文档子数组的对象内的布尔值?

如何使用 Autopopulate Mongoose Mongodb 选择要检索的字段?

如何在本地使用带有 express 的 graphql 和带有 mongoose 的 mongodb 来检索文档?