Home > Back-end >  MongoDB Add More users to a field
MongoDB Add More users to a field

Time:08-19

I have a MongoDB collection for company users. Inside of this, the company is able to add in their team members to a field called: "teamMemberDetails"

For example, see a demo of what it currently looks like when I put a user into the DB through my API.

{
    "teamMemberDetails": [
        {
            "memberEmail": "[email protected]"
        }
    ],
    "teamMembers": "0",
    "_id": "62fc49b53bcb32ca823466dc",
    "companyTitle": "Working Acc!v2",
}

It's also worth mentioning the schema is:

const CompanyProfileSchema = new mongoose.Schema(
    {
        companyTitle:{type:String, required: true, unique: true, default: ""},
        companyPassword:{type:String, required: true, default: ""},
        centralEmail:{type:String, required: true, unique: true, default: ""},
        description:{type:String, required: true, default: ""},
        inviteToken:{type:String, required: true, default:""},
        industry:{type:String, required: true},
        employees:{type: Number},
        companyImage: {type:String, required: false, unique: false, default: ""},
        locationCity:{type:String, required: false, unique: false, default: ""},
        industry:{type:String, required: false, unique: false, default: ""},
        country:{type:String, required: false, unique: false, default: ""},
        teamMembers: {
            type: String, required: true, default: 0
        },
        teamMemberDetails: {
            memberName: String, default: "",
            memberEmail: String, default: "",
            memberRole: String, default: ""
        },
        highlights: {type: Array},
        isAdmin:{
            type: Boolean,
            default: false,
        },
        isVerified:{
            type: Boolean,
            default: false,
        },
        accountLevel: {type: Array},
        emailAuthorised: { type: Boolean, default: false},
        invitedUsers: {type: Array}
    },
);

This user was placed in with an API request like below:

//UPDATE Company - PROFILE
router.put("/updateCompany/:id", async (req, res) => {
  try {
    const updatedUser = await CompanyProfile.findByIdAndUpdate(
      req.params.id,
      {
        $set: req.body,
      },
      { new: true }
    );
    res.status(200).json(updatedUser);
  } catch (err) {
    res.status(500).json(err);
  }
});

However, i'd like this team members detail to build, for example i'd like something like this:

    "teamMemberDetails": [
        {
            "memberEmail": "[email protected]", "[email protected]", "[email protected]", "[email protected]"
        }
    ],

Basically, I want to concatenate onto this field with several ongoing email addresses as they add new users.

Any ideas?

CodePudding user response:

Change your schema for memberEmail so that it accepts an array. ie. [String]:

teamMemberDetails: {
            memberName: String, default: "",
            memberEmail: [String], default: [],
            memberRole: String, default: ""
        },

and to update the document:

const teamMemberDetailsObject = 
{
  "memberEmail": [
    "[email protected]", 
    "[email protected]",
    "[email protected]", 
    "[email protected]"
  ]
}

if you'd like to initialize the array of emails, you can do that like this:

const updatedUser = await CompanyProfile.findByIdAndUpdate(
      req.params.id,
      {
        $set: {teamMemberDetails: teamMemberDetailsObject}
      },
      { new: true }
    );

If you'd like to add new emails to the memberEmail array in the same document in the collection, you can use the following:

const updatedUser = await CompanyProfile.findByIdAndUpdate(req.params.id, {
  $addToSet: {
    "teamMemberDetails.memberEmail":"[email protected]"
  }
  },
  { new: true }
);

CodePudding user response:

Using $set and $push together, you can update other values on the document as well as push new items to the memberEmail array.

By using $push, you can add new items to the array.

// model 
teamMemberDetails: {
    memberName: String, default: "",
    memberEmail: [String], default: [],
    memberRole: String, default: ""
},

// dummy payload
const memberEmail = [
    "[email protected]", 
    "[email protected]",
    "[email protected]", 
    "[email protected]"
]

// Update call
const updatedUser = await CompanyProfile.updateOne(
    {_id: req.params.id},
    {
        $set: req.body,
        $push: {
            teamMemberDetails.memberEmail: memberEmail
        }
    },
    { new: true }
);

Here's a working example.

  • Related