Reputation: 792
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.
Upvotes: 6
Views: 447
Reputation: 16805
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]
}
Upvotes: 3