首页 > 解决方案 > 如何在一个命令中使用 mongoose 检索配置文件和用户模式?

问题描述

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

这是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')

标签: node.jsmongoose

解决方案


您需要在 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 },
});

推荐阅读