Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

368
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda