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

126
Visualizações
Update multiple or single object in an array with specified data from request

I am not great with MongoDB advanced technique. My record in mongo db collection

    {
        "_id": ObjectId("1"),
        "manager": ObjectId("12345"),
        "code": "PS",
        "title": "Performance System",
        "users": [
            {
                "_user": ObjectId("1"),
                "role": "Member",
            },
            {
                "_user": ObjectId("2"),
                "role": "Member",
            },
            {
                "_user": ObjectId("3"),
                "role": "Member",
            }
        ],
    }

Node.js / ExpressJS

I created API to update the array like below but did not work.

const updateProjectMember = asyncHandler(async (req, res) => {
  const { userID, role } = req.body.userData;

  try {
    const project = await Project.updateMany(
      { _id: req.params.projectID },
      { $set: { "users.$[selectedUser].role": role } },
      { arrayFilters: { "selectedUser._user": { $in: userID } } }
    );
    res.status(200).json(project);
  } catch (error) {
    res.status(400);
    throw new Error(error);
  }

I use the API parameter to get project ID. Here the request body data

{
  userID : ["2","3"];
  role: "Admin"
}

So the API will get array of userID to match and set all "role" field to "Admin" to all matched.

I wanted the data to be like this

{
        "_id": ObjectId("1"),
        "manager": ObjectId("12345"),
        "code": "PS",
        "title": "Performance System",
        "users": [
            {
                "_user": ObjectId("1"),
                "role": "Member",
            },
            {
                "_user": ObjectId("2"),
                "role": "Admin",
            },
            {
                "_user": ObjectId("3"),
                "role": "Admin",
            }
        ],
    }

Am I doing right practice? If it bad practice, what is the best way to solve this.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The query is fine. Just make sure that you pass the value with the exact type as in the MongoDB document.

var mongoose = require('mongoose');

const updateProjectMember = asyncHandler(async (req, res) => {
  const { userID, role } = req.body.userData;
  userID = userID.map(x => mongoose.Types.ObjectId(x));

  try {
    const project = await Project.updateMany(
      { _id: mongoose.Types.ObjectId(req.params.projectID) },
      { $set: { "users.$[selectedUser].role": role } },
      { arrayFilters: { "selectedUser._user": { $in: userID } } }
    );
    res.status(200).json(project);
  } catch (error) {
    res.status(400);
    throw new Error(error);
  }
}
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