0

How to have user and profile together?

This is how User schema defined:

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

and Profile schema:

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' },
});

How can I retrieve in one command/line the profile when I ask for user?

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

I have try populate but it is not works:

User.findOne({ email: 'blabla@gmail.com' }).populate('profile')
  • Please notice: I don't want to have profile in user in the same schema.
Jon Sud
  • 10,211
  • 17
  • 76
  • 174

1 Answers1

0

You would need to link the Profile inside the 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 },
});
Simon Thiel
  • 2,888
  • 6
  • 24
  • 46
  • There is solution which the user schema doesn't need to changed? – Jon Sud Sep 23 '19 at 14:15
  • You are looking for a reverse populate feature which is not available yet. Here find possible solutions: https://stackoverflow.com/questions/37691476/mongoose-reversed-population-i-e-populating-a-parent-object-based-on-the-ref – Simon Thiel Sep 23 '19 at 14:26
  • In general the cleanest solution is to structure you schema as suggested and directly populate the required data. – Simon Thiel Sep 23 '19 at 14:27