mongoose saving a model with a reference

296 Views Asked by At

I have a model that looks something like this

var UserSchema = new Schema({
    id:                 ObjectId,
    username:           { type: String, trim: true, required: true, unique: true, lowercase: true },
    location:           [{ type: ObjectId, ref: 'Location', required: false }],
    attachments:        [{ type: ObjectId, ref: 'Attachment', required: false }]
})

When a user registers I need to create the location and attachments objects before I save/create the user to get those ObjectIds. I feel like the way I am doing this might be wrong and that is why it is confusing or there is something I am missing.

My question is how do I go about saving those collections before I save the user collection so I can have those references included in my user collection.

Similar to this question, except multiple references.

1

There are 1 best solutions below

1
Kundu On BEST ANSWER

Use mongoose hooks to solve the dependency relations. if you want to get the location attachment before saving the user use pre hooks otherwise use post hooks.