I'm currently trying to wrap my head around creating a many-to-many relationship in mongodb/mongoose.
I have two Schemas:
// User Schema
var UserSchema = mongoose.Schema({
email: {
type: String,
index:true
},
name: {
type: String
},
tasks:[{type:mongoose.Schema.ObjectId, ref: 'Tasks'}]
});
and
// Tasks Schema
var TaskSchema = mongoose.Schema({
name: {
type: String,
index: true
},
description: {
type: String
},
status:{
type: String
},
});
The idea here, is that each user can take on a task and the task would have it's own status for each user (e.g. notStarted, inProgress, Complete, Failed). This status would change as the user progresses through the task. Each user would see the same tasks(i.e. name + description), but would have a different status associated with it. Additionally, each task has it's own status (Available, Hidden), which would dictate if the users can see the task or not. This would not be unique for each user.
This is my thought process so far:
I'm thinking that I can nest the objectIds of every task in with the user along with the status. For example:
{
email: "Bob@bob.com"
name: "Bob",
tasks: {
{ _id: 001, status: "Active"},
{_id: 002, status: "inProgress"},
{ _id: 003, status: "Failed"}
}
},
{
email: "Mary@mary.com"
name: "Mary",
tasks: {
{ _id: 001, status: "Failed"},
{ _id: 002, status: "Active"},
{ _id: 003, status: "Active"}
}
}
However, this means that whenever I create a new task, I need to add it to the task list of all users, with the status set to a default (e.g. notStarted). Additionally whenever I add a new user, I need to get all tasks and add them to the user's list of tasks.
This seems sort of clunky to me, and I feel like there must be a better way. If this is the best way to do it, I'm not quite sure what I would use to write this. I was thinking maybe use addFields or would Push be more appropriate? Or would that create arrays that grow without bound? which might not be the best idea since it's a Mongo anti-pattern from what I've read?
I also found this post that's sort of related, but it's from ~6 years ago, and I think I need a little bit more depth or code examples.
Any help would be much appreciated!