node.jsmongodbmongoosemongoose-schemamongoose-populate

create a single collection MongoDB schema mapping both projects and employees that does not duplicate data?


Collections Employee and Project maintain a history of project allocations for employees and projects.

I created a collection schema but it duplicates data.

How can I create a single MongoDB collection schema mapping both projects and employees that does not duplicate data?

const employeeSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    project: {
        start: {
            type: Date,
            required: true
        },
        end: {
            type: Date,
            required: true
        },
        project: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Project',
            required: true
        }
    },
}

const projectSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    employee: {
        start: {
            type: Date,
            required: true
        },
        end: {
            type: Date,
            required: true
        },
        project: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Employee'
        }
    }
});

Solution

  • You could try something like this - no duplication, and this will allow many employees to be enrolled on many projects - if that is what you are looking for ? It isn't "single collection", but I think that would be a tricky solution...

    const employeeSchema = mongoose.Schema({  
        name: {  
            type: String,  
            required: true  
        }  
    }); 
    
      
    const projectSchema = new mongoose.Schema({  
        name: {  
            type: String,  
            required: true  
        }  
    });  
      
    const enrolledSchema = new mongoose.Schema({  
        start: {  
            type: Date,  
            required: true  
        },  
        end: {  
            type: Date,  
            required: true  
        },  
        employee: {  
            type: mongoose.Schema.Types.ObjectId,  
            ref: 'Employee'  
        },  
        project: {  
            type: mongoose.Schema.Types.ObjectId,  
            ref: 'Project'  
        }  
    });