Prebuild Mongoose Inline Document

I have two models, one of which is User , and the other is Reservation . I want to embed a User object in every reservation. The user has already been created and is stored in the user collection. When I try to create a new backup object, my User object goes through the pre-save method and ultimately fails because there is a unique username field. Is there a way around this precautionary method when embedding objects in another collection, or is my approach completely wrong? My code for the backup scheme. Thanks!

 import User from './../users/users.model'; const Schema = mongoose.Schema; export default new Schema({ user: { type: User } }); 

Edit: when I clearly define the scheme, it bypasses the pre-save method (which makes sense), but if I want to change the scheme, I need to change it in two different places.

+5
source share
1 answer

You can follow this process.

Instead of referencing the complete collection , you should specify a specific user for the Reservation document. When you save or create a new Reservation information that you must pass to the user id in order to save as an ObjectId and reference the id on the user model in order to reference the user use the ref model. therefore, you can easily populate the user from the reservation .

as:

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

instead

 user: { type: User } 

Or , if you want to implement a user scheme in a backup scheme , you can use as

 user: { type: [User] } 
+3
source

All Articles