Home > Blockchain >  Update multiple or single object in an array with specified data from request
Update multiple or single object in an array with specified data from request

Time:03-22

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.

CodePudding user response:

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);
  }
}
  • Related