Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Embedded Document Pre Save

I have two models, one of them is User and the other one is Reservation. I want to embed a User object to every Reservation. User is already created and stored in Users collection. When I try to create a new Reservation object, my User object goes through pre save method and eventually fails because there is unique username field. Is there a way to bypass that pre save method when embedding objects to another collection or is my approach it completely wrong? My code for Reservation schema. Thanks!

import User from './../users/users.model';
const Schema = mongoose.Schema;

export default new Schema({
  user: {
    type: User
  }
});

Edit: When I define the Schema explicitly it bypasses the pre save method (which makes sense), but if I want to change the Schema, I need to change it in two different places.

like image 435
Arda Keskiner Avatar asked Oct 18 '22 10:10

Arda Keskiner


1 Answers

You can follow this process.

Instead of refer full collection you should refer a specific user for a Reservation document .When you will save or create new Reservation information you should pass user id to store as ObjectId and refer that id to user model to refer user model use ref keyword. so you can populate easily user from Reservation model.

like:

user:{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }

instead of

user: {
    type: User
  }

Or if you want to embedded user schema in reservation schema then can use like

user: {
        type: [User]
      }
like image 85
Shaishab Roy Avatar answered Oct 21 '22 02:10

Shaishab Roy