Reputation: 270
I have the following schema structure:
var ProgramSchema = new Schema({
...
networks: [NetworksSchema]
});
var NetworksSchema = new Schema({
payments: [NetworkPaymentsSchema],
...
});
var NetworkPaymentsSchema = new Schema({
...
amount: { type: Number, get: genFunc.getCurrency, set: genFunc.setCurrency, required: true }
});
Whenever I create() or save() a ProgramSchema, the getter and setter in NetworkPaymentsSchema are not called.
So far I tried to call the setter this way:
NetworkPaymentsSchema.path('amount').set(genFunc.setCurrency);
Doesn't seem to work either.
Thanks for help!
Upvotes: 0
Views: 537
Reputation: 75
Please note that variable definition order matters in JavaScript. Upon running your snippet ProgramSchema will look like this:
var ProgramSchema = new Schema({
...
networks: [undefined] // Which is effectively equivalent to mongoose.SchemaTypes.Mixed or {}
});
This happens because at the moment of definition of ProgramSchema neither NetworkSchema nor NetworkPaymentSchema is defined. Though they are both declared due to hoisting, which prevents program from crashing with ReferenceError. Thus there is no any relation between your schemas.
So to fix your problem you must move definitions of sub-schemas above the ProgramSchema's one. I.e. your code must look like the following (notice the order of schemas definition):
var NetworkPaymentsSchema = new Schema({
...
amount: { type: Number, get: genFunc.getCurrency, set: genFunc.setCurrency, required: true }
});
var NetworksSchema = new Schema({
payments: [NetworkPaymentsSchema],
...
});
var ProgramSchema = new Schema({
...
networks: [NetworksSchema]
});
I have tested on MongoDB 2.6.4 and Mongoose 3.8.17 and it seems to work.
Upvotes: 1
Reputation: 1590
I have used the following before which worked for me. I assume you are saving prices in cents instead of a float. You shouldn't have to call the setter, mongoose should do that for you. Just save the data.
Schema: {
amount: {type: Number, get: getPrice, set: setPrice }
}
function getPrice(num){
return Number((num/100).toFixed(2));
}
function setPrice(num){
return Number(num)*100;
}
Upvotes: 0