I'm having troubles while trying to handle arrays of objectIds (for further population in mongoosejs models), I hope you can help me. here is the context:
I have a little nodejs / angularjs app where I have products and providers. The products have a property providers which is an array of objectId's, referencing providers. Here is the schema:
var productSchema = new Schema({
name : { type: String, required: true, trim: true},
providers : [{ type: Schema.Types.ObjectId, ref: 'provider' }]
});
The user is able to query the list of providers through the GUI. Then he can select which provider are available for each product (checkboxes). Internally it means that I am pushing the hex strings corresponding to the providers _id into the array providers of my angular product model, then the request is sent to the nodejs/express server.
Here is the problem, I've been trying to turn the hex strings into objectId in many ways, I just can't find the right way. My last attempt was with the "presave" function of mongoose. Here the current version.
productSchema.pre('save', function (next) {
var err = new Error('There was an error when trying to add the providers id as objectId'),
i = 0;
for (i = 0; i < this.providers.length; i++) {
this.providers[i] = mongoose.Types.ObjectId(this.providers[i].toString())
}
next(err);
});
Any help is welcome, I thought mongoose would just handle everything alone. What's the normal way to do this? (the pre save was just an idea)
Thanks for reading