UX Guy
UX Guy

Reputation: 257

How do I structure my data with mongodb?

Please tell me if this is an appropriate solution to my problem:

As a manager of a franchise, you can log in. There's a list of all your employees. On the left it says:

Company Name

Store 1

Store 2

So here's an example

Bob's Grocery Stores

Chicago Store

New York Store

So currently my idea is to have 2 models. A user model and a company model. I'm using a second company model because if the store name changes with one user, it needs to change with every user. Then I user a ref to that company within the user document.

var CompanySchema = new Schema({
    name: {
        type: String,
    },
    store: {
        type: Array
    },
 });

I would have the sections inside the 'store' property because different stores have different sections.

So far I think everything is correct. My question is how do I assign a user to a specific section in a store. Would it be user.company.store[3].section[1]? Wouldn't the indexOf values for section/store change if a section/store get deleted? How do people generally go about doing something like this? I'm basically creating the same thing as folder/file directory.

Upvotes: 0

Views: 117

Answers (1)

Dave Briand
Dave Briand

Reputation: 1734

I'd do this:

Schemas:

var UserSchema = new Schema({
    name: { type: String },
    company: type: Schema.Types.ObjectId, ref: 'Company',
    stores: [{type: Schema.Types.ObjectId, ref: 'Store'}]
    sections: [{type: Schema.Types.ObjectId, ref: 'Sections'}]
})

var CompanySchema = new Schema({
    name: {
        type: String,
    },
    store:{type: Schema.Types.ObjectId, ref: 'Store'}
 });

var StoreSchema = new Schema({
    name: {
        type: String,
    },
    sections: [{type: Schema.Types.ObjectId, ref: 'Section'}]
 });

var SectionSchema = new Schema({
    name: {
        type: String,
    }
});

The value in the "ref" key is the name of the corresponding Model. So CompanySchema has a corresponding Company model.

The nice thing about actually storing object ids is you can now use 'populate' to get the references objects.

I'm storing "sections" directly inside the UserSchema for simplicity and direct access.

I'd then index the arrays in the user schema to make access even faster.

You'd have to also write some middleware to take care of removing stores/sections to ensure they're also removed from any users that reference them.

Upvotes: 1

Related Questions