0

I have a project with the following document flow.

Users -> Accounts -> Projects

Users

  • Users have specific roles

Accounts

  • CRUD conditioned by User role
  • Specific users will have access to individual accounts. I was thinking to add an array userGroup with user id's?

Projects

  • Nested under Accounts related to a single accountToken ID
  • CRUD conditioned by User role
  • Specific users will have access to individual projects.

Here are example Schema models simplified for demo purposes.

UserSchema.js:

const UserSchema = new mongoose.Schema({
    email: {
      type: String,
      required: [true, 'Please add an email'],
      unique: true,
    },
    role: {
      type: String,
      enum: ['admin', 'user'],
      default: 'user'
    }
  });

  module.exports = mongoose.model('User', UserSchema);

AccountSchema.js:

const AccountSchema = new mongoose.Schema({
    accountName: {
      type: String,
    },
    accountToken: {
      type: String
    }
  });

  module.exports = mongoose.model('Account', AccountSchema);

ProjectSchema.js:

const ProjectSchema = new mongoose.Schema({
    projectName: {
        type: String,
    },
    projectType: String,
    projectToken: String
})

module.exports = mongoose.model('Project', ProjectSchema);

I am stuck on the best way to setup nested or sub-document Schema Relations and the best way to relate the data between each other. Any guidance and suggestions would be a huge help! Thanks!!!

1 Answer 1

1

Try this;

const UserSchema = new mongoose.Schema({
email: {
  type: String,
  required: [true, 'Please add an email'],
  unique: true,
},
role: {
  type: String,
  enum: ['admin', 'user'],
  default: 'user'
}
});

module.exports = mongoose.model('User', UserSchema);

const AccountSchema = new mongoose.Schema({
  userId: {
     type: mongoose.Schema.Types.ObjectId,
     required: true,
     ref: 'User'
 },
 accountName: {
     type: String,
 },
accountToken: {
    type: String
}
});

module.exports = mongoose.model('Account', AccountSchema);

const ProjectSchema = new mongoose.Schema({
  accountTokenId:{
      type: String
  },
  projectName: {
      type: String,
  },
  projectType: String,
  projectToken: String
})

module.exports = mongoose.model('Project', ProjectSchema);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @joshua-oweipadei. I ended up nesting the Project Schema inside the Account Schema projects: [ProjectSchema] and then using virtuals for the id. Probably not the best but it's working at the moment. Example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.