Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Activity model with dynamic reference

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!

like image 324
maumercado Avatar asked Oct 28 '13 23:10

maumercado


1 Answers

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

like image 84
keithics Avatar answered Sep 27 '22 18:09

keithics