These are chat archives for Automattic/mongoose

19th
Dec 2016
Paul "Joey" Clark
@joeytwiddle
Dec 19 2016 04:43

@lundgren2 you need the same answer Kiran got. In your Customer schema, refer to the CustomerAddress document like this:

CharCode: String,
customerAddress: { type: Schema.Types.ObjectId, ref: 'CustomerAddress' },
…

Then populate that field when you fetch:

CustomerModel.find({…}).populate(‘customerAddress’);

(Address / Addons whatever ;) )

Tobias Lundgren
@lundgren2
Dec 19 2016 12:47
Thanks @joeytwiddle I will look at it! :)
But how will it know what customerAddon field that it’s right for the current customer? Where CustomerAddons.customerId = Customer.CardCode
Paul "Joey" Clark
@joeytwiddle
Dec 19 2016 12:50
It will bring the whole document from the CustomerAddons collection and place it into the field, instead of the ObjectId that was there before.
Tobias Lundgren
@lundgren2
Dec 19 2016 12:51
Ah I see! And then I have to search for the right customerAddons in the response ?
Paul "Joey" Clark
@joeytwiddle
Dec 19 2016 12:52
The customerAddon field needs to be the _id of the CustomerAddon document. populate() looks it up by its _id and replaces it with the document.
If you wanted to look it up by something that isn't the _id then you would have to do that manually.
Tobias Lundgren
@lundgren2
Dec 19 2016 12:54
Hmm, ok! I think the best way to do that is to change the design so I can use the customerAddons _id to get the correct field...
I guess that I fix that where I save the CustomerAddon records?
Paul "Joey" Clark
@joeytwiddle
Dec 19 2016 12:55
That would be the popular way :)
An example: http://mongoosejs.com/docs/populate.html
They have put an underscore on the _creator field to make it clear its an ObjectId, but that's entirely optional.
Tobias Lundgren
@lundgren2
Dec 19 2016 13:11
Ok thanks :) I will try this way!