Mongoose to update MongoDB collection of array of number ids

Viewed 16

I have the following user Schema

const UserSchema = new mongoose.Schema({
  name: String,
  username: String,
  email: String,
  picture: String,
  id: { type: String, unique: true },
  accessCount: Number,
  appliedIds: [Number],
  general: {
   citizenship_code: String,
   gender: String,
   currentLocation: String,
   phone: String,
 }
});

And I wanna update the appliedIds field. The appliedIds field is an array of numbers that will have an indeterminate number of indexes.

My function is as follow:

router.route('/myCustomRoute/:id/apply')
  .post(async (req, res) => {
     const { nModified } = await Job.findOne({ id: req.params.id }).updateOne({
       $addToSet: { applicants: req.body.applicantId },
     });

     const test = await User.findOneAndUpdate({ id: req.body.applicantId}, { appliedIds: req.params.id })

Obviously, the applicantId is getting replaced entirely here, how can I just add a new item in this array instead of replacing it entirely?

1 Answers

You'll want to push to the appliedIds fields in your findOneAndUpdate call.

const test = await User.findOneAndUpdate(
  { id: req.body.applicantId},
  { $push: { appliedIds: req.params.id } }
)

MongoDB $push

Related