简体   繁体   中英

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

I am not great with MongoDB's advanced techniques. My record in the MongoDB 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 the project ID. Here is the request body data:

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

So the API will get an array of userID to match and set all "role" fields 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 the right practice? If it is bad practice, what is the best way to solve this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM