Poot87
Poot87

Reputation: 105

How should I approach my back end design using the MEAN stack?

This is maybe more a case of looking for advice. However, I will supply sample code as an example of what I want to achieve. I am trying to build my first back end system and I keep running into problems with the design.

My MongoDB database consists of 4 major parts - Profiles, Teams, Drafts and Users. The profile (being the main data which sources everything using IDs) schema has properties to hold arrays with the Teams and Drafts IDs. The idea is that when the profile is served it will populate all those properties with the relevant data by using the IDs.

Example of the Profile schema using Mongoose:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserProfileSchema = new Schema({
        Name : String,
        Email : String,
        Admin : Boolean,
        Status : Number,
        UserID : String,
        PrivateProfile: Boolean,
        Drafts: [String], //This array holds the draft IDs
        Teams:[String] //Holds the team profiles IDs 
    });

module.exports = mongoose.model('UserProfile', UserProfileSchema);

Example of Team Profile Schema using Mongoose:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var TeamProfileSchema = new Schema({
        Name : String,
        CaptainID : String,
        CaptainName : String,
        Members : [String], //Array of user IDs
        DateCreated : Boolean,
        Reputation : Number
    });


module.exports = mongoose.model('TeamProfile', TeamProfileSchema);

Example of a route to find all the Team Profiles the user is the Captain of and fetch all the members associated with that team:

router.route('/teams/captain/:user_id')
.get(function (req, res) {
TeamProfile.find({
    CaptainID : req.params.user_id
}, function (err, teams) {
    if (err)
        res.send(err);

    for (var x in teams) {
        var membersArray = [];
        for (var i in teams[x].Members) {
            var ID = teams[x].Members[i];
            UserProfile.find({
                UserID : ID
            }, function (err, profile) {
                if (err)
                    res.send(err);
                membersArray.push(profile);
            });
        }
        teams[x].Members = membersArray;
        console.log(teams[x].Members);
    }
    res.json(teams);
});
})

I understand that the route will not work, but how do I pull this off? I used a more vanilla approach only for the purpose to explain what I want to achieve. Any help would be highly appreciated.

Upvotes: 1

Views: 44

Answers (1)

Munish Kapoor
Munish Kapoor

Reputation: 3339

I advise you to use combination of denormalization and normalization.

because MongoDB is not a relational database.

denormalization is much faster then normalization. You don't need to use relationship anymore.

You can read this article hope may helpfull to you.

Cheers

Upvotes: 1

Related Questions