Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

367
Views
Adding documents to a Many to Many relationship in Mongoose (MongoDB)

I have a User collection and a Task Collection. Many Users can have many Tasks, and Many Tasks can have many Users. The proper way I believe in doing this is the following models:

var UserSchema = new Schema({
    id: ObjectId,
    username: { type: String, required: true },
    assignments: [ {type : mongoose.Schema.ObjectId, ref : 'Assignment'} ]
});

var TaskSchema = new Schema({
    id: ObjectId,
    title: { type: String, default: '' },
    information: { type: String, default: '' },
    assignments: [ {type : mongoose.Schema.ObjectId, ref : 'Assignment'} ]
});

var AssignmentSchema = new Schema({
    id: ObjectId,
    isCompleted: { type: Boolean, default: false },
    completionDate: { type: Date, default: null },
    tasks: [ {type : mongoose.Schema.ObjectId, ref : 'Task'} ],
    users: [ {type : mongoose.Schema.ObjectId, ref : 'User'} ]
});

If the above models are correct, how do you insert a Task with multiple user assignments? I understand that you would create the Task document first to get its ObjectId, but after that would you just insert all of the assignments into the Assignment collection (with their proper Task and User objectId's) and thats it? Or would I have to insert all of the assignments then edit each individual User and Task to insert the AssignmentId into their assignments property.

I am sure there is a stack over flow question like this already, but I have not been able to find one. Any help is appreciated!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I believe you have the answer in your question.

Create a new task, capture the task id. Then find or create a new user, edit or add the task’s id, capture the user id. Add the user id to the task. Repeat for additional users.

I believe this is what you say in the final part of your question?

I don’t see why this cannot work.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!