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

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

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 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