Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

369
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda