Is it possible in Mongoose to create a formula field on one model that takes data in from a related model and updates automatically when the related record changes. Say I have a todo model and a user model. On the todo, i would like to have a user_id and a user_email field. The user_email will take the email field on the related user. If the user record is changed, the user_email field will automatically be updated on the todo to reflect the change. This way, I can use my client application to query for todos with just an email address. Here are the models I had in mind:
module.exports = mongoose.model('Todo', {
description : String,
User_id : mongoose.Schema.Types.ObjectId,
isCompleted : Boolean,
createdDate : Date,
User_email : String
});
module.exports = mongoose.model('User', {
name : String,
email : String
});
Yes, it is possible! According to the example would be done this way.
User.pre('save', function(next){
var nowDocument = this;
User.findById( doc._id, function(err, beforeDocument){
if(err) retrun next(err);
// Here is to compare and modify*
next();
});
});
*To this point the data is validated.