Reputation: 147
I have a 2 schemas which needs the data in each other during saving operation. When model1 is saved model1's id would be needed by the model2 and on completion model1 would need the id of model2.
express.js
SCHEMA1.full_name = fullName;
SCHEMA1.other_fields = other_details;
var variableName = 'inside the controller';
schema2 = new schema(req.body);
SCHEMA1.save(function (err, result){
});
SCHEMA1.js
var SCHEMA1 = mongoose.Schema({
full_name: String,
other_fields : String//etc
schema2_foreign_field:{
type: Schema.Type.ObjectId,
ref: 'schema2'
}
})
SCHEMA1.pre('save', function(){
var fullName = this.full_name;
var otherFields = this.other_fields;
var schema2= this.model('schema2')
schema2.name = 'Bryan';
schema2.clocking_time = Date.now();
schema2.save();
var schema2Id = schema2._id;
/********************************************
* how can i get schema2Id above into pre *
* hook after the data has been saved *
********************************************/
//perform operation inside schema and compare
//result with controller variableName
})
SCHEMA1.post('save', function(){
SCHEMA1.schema2_foreign_field=schema2Id;//obtained from above
SCHEMA1.save();
})
Upvotes: 0
Views: 46
Reputation: 125
Declare a variable inside the schema and use it within the two hooks i.e. var variableName='';
SCHEMA1.pre('save', function(){
......others
variableName= schema2._id
})
Schema1.post('save', function(){
SCHEMA1.schema2_foreign_field=variableName;//obtained from above
SCHEMA1.save();
});
Pre hook variable can now be used in post hook function
Upvotes: 1