0

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.

Stennie
  • 63,885
  • 14
  • 149
  • 175
gmaniac
  • 940
  • 1
  • 17
  • 33
  • Do the location and attachments documents already exist in the database, or are you creating unique ones simultaneously with the new user, or do you need to check if they already exist before creating? – chrisbajorin Nov 17 '14 at 19:26
  • @cdbajorin creating new ones at the creation of a new user, I do not need to check if the attachments or location already exist. – gmaniac Nov 17 '14 at 21:00
  • The `_id` value of a new `Location` or `Attachment` object is immediately available as `_id` is populated client-side rather than on the server. – JohnnyHK Nov 18 '14 at 18:15
  • @JohnnyHK correct so if I do `var newloc = new Location(data);` and then assign it to the user `user.location = newloc._id;` that works I was wondering if I was doing it right or the using best practices this way. I feel like it is turning a non-relational db into a relational db I want to go with best practices whenever I can. Thanks for the comment! – gmaniac Nov 18 '14 at 19:11
  • I'm not sure I understand why you're doing it this way. I think you're trying to create too many collections. Based on your response to my question, it seems location/attachments have a 1:1 relationship with a user. Do those have any other associations or uses? Why bother create collections for them? – chrisbajorin Nov 18 '14 at 19:41
  • you are correct, currently I only have a 1:1 with user to location and to attachments on user creation. however after a user is created users will be linking for location and attachments making it 1:many let me know if I am not making sense. – gmaniac Nov 18 '14 at 19:50

1 Answers1

0

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.

Kundu
  • 3,944
  • 3
  • 16
  • 21
  • The problem I was running into was that I couldn't access the data in the `pre` I was only able to access whatever was associated with the model through `this` – gmaniac Nov 18 '14 at 16:18