Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

MongooseJS schema relation

MongooseJS schema relation


I have MongooseJS Schema as follow:

var UserSchema = new Schema({
    name            : String,
    app_key         : String,
    app_secret      : String,
    tasks           : [{ type   : Schema.ObjectId, 
                            ref : 'Task'}]

var ActionSchema = new Schema({
    name            : String,
    description     : String,
    module          : String

var enumTaskState = ['New', 'Indexing', 'Idle', 'In Queue', 'Working'];
var TaskSchema = new Schema({
    name            : String,
    lastPerformed   : Date,
    folder          : String,
    actions         : [{type    : Schema.ObjectId, 
                        ref     : 'Task'}],
    user            : { type    : Schema.ObjectId, 
                        ref     : 'User'},
    status          : { type    : String,
                        enum    : enumTaskState,
                        default : 'New'}

Problem is, when I set a task's user, do I manually have to go to the user and add a task there too? This seems like extra work (redundancy), is there an option in mongoosejs that will allow me to specify the relations it will handle everything by itself? Thanks.

Problem courtesy of: 0xSina


MongoDB is not a relational database, it is a document based based database.

You can get a user's list of tasks by querying the TaskSchema and looking for the user you want. Just make sure to add an index so it will be a fast query:

user: {type: Schema.ObjectId, ref: 'User', index: true}
Solution courtesy of: staackuser2


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

MongooseJS schema relation


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription