I want to create an activity model in order to show a timeline kind of thing with my application, but I don't know exactly how to dynamically reference a collection in a mongoose schema. Im using mongoose (3.6.20)
In what I have so far the actor is always a user, but the _object can be a user or a post.
This is kind of what I have:
userSchema = new Schema({
_id: ObjectId;
name: String
});
postSchema = new Schema({
_id: ObjectId;
author_id: String, ref: User
});
What I want to do is:
activitySchema = new Schema({
_object: { String: Id of the thing, ref:'can be user or post'} // Object that the verb occurred on... can be a post or a user
actor: { type: String, ref: 'User' },
action: { type: String, default: ""}, //ex: has replied to:, or started following:
});
How can I solve this using dynamic references with mongoose if possible, and how will I populate it?
Thank you!
updated 2017..
you can now have dynamic refs using refPath or even multiple dynamic refs.
var userSchema = new Schema({
name: String,
connections: [{
kind: String,
item: { type: ObjectId, refPath: 'connections.kind' }
}]
});
The refPath property above means that mongoose will look at the connections.kind path to determine which model to use for populate(). In other words, the refPath property enables you to make the ref property dynamic.
http://mongoosejs.com/docs/populate.html Dynamic References
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With