0xSina
0xSina

Reputation: 21553

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.

Upvotes: 3

Views: 1498

Answers (2)

Michelle Tilley
Michelle Tilley

Reputation: 159105

To elaborate on emostar's answer:

You're trying to use MongoDB like a relational database. You're giving Users a list of Tasks, but each Task is referencing a User. In a typical MongoDB schema, you'd figure out how you want to use the models in your app and just embed the documents where it makes sense (e.g. if Users contains an array of Tasks, there's no need for a task to have a reference to it's owner--just look at the User that owns the collection).

Upvotes: 4

staackuser2
staackuser2

Reputation: 12412

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}

Upvotes: 6

Related Questions