node.jsmongodbmongoose

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!


Solution

  • Why not acitivitySchema have both?

    activitySchema = new Schema({
        user:{ type: Schema.Types.ObjectId, ref:'User' }, 
        post:{ type: Schema.Types.ObjectId, ref:'Post' }, 
        actor: { type: String, ref: 'User' },
        action: { type: String, default: ""}, //ex: has replied to:, or started following:
    });
    

    When you get the mongoose object, just call populate('user') and populate('post'). It will fill the user or post based on what was saved. Mongodb is extremely efficient in doing this.