Mongoose - REST API - Schema With Query to different model
In this case, the best way to handle it would be to add a post save hook to your Activity
schema to store the most recent _id
in the latest_activity
path of your User
schema. That way you'd always have access to the id without having to do the extra query.
ActivitySchema.post('save', function(doc) { UserSchema.findOne({username: doc.owner}).exec(function(err, user){ if (err) console.log(err); //do something with the error else if (user) { user.latest_activity = doc._id; user.save(function(err) { if (err) console.log(err); //do something with the error }); } });});
Inspired by @BrianShambien's answer you could go with the post save, but instead of just storing the _id
on the user you store a sub doc of only the last activity. Then when you grab that user it has the last activity right there.
User Model
username : {type: String, unique: true},age : {type: Number},last_activity: ActivitySchema
Then you do a post save hook on your ActivitySchema
ActivitySchema.post('save', function(doc) { UserSchema.findOne({username: doc.owner}).exec(function(err, user){ if (err) errHandler(err); user.last_activity = doc; user.save(function(err) { if (err) errHandler(err); }); });});
**********UPDATE************
This is to include the update to the user if they are not an owner, but a particpant of the the activity.
ActivitySchema.post('save', function(doc) { findAndUpdateUser(doc.owner, doc); if (doc.participants) { for (var i in doc.participants) { findAndUpdateUser(doc.participants[i], doc); } }});var findAndUpdateUser = function (username, doc) { UserSchema.findOne({username: username}).exec(function (err, user) { if (err) errHandler(err); user.last_activity = doc; user.save(function (err) { if (err) errHandler(err); }); });});