$addToSet / $set does not push the ObjectId

  javascript, mongoose, node.js, set, strapi

Currently using Strapi v3.5.3ce. I have a post model with has relation with category model.

A post already exist, but I want to update the post with multiple categories, so I thought of using $addToSet / $set in order to eliminate duplicates added.

But it doesn’t seem to push.

ways I have tried are

// with $set
const up = {
  $set: { categories: [ '6073ac8f68f6971f3edfc898', '6073ac8f68f888f3edfc111' ] },
  ...update
}

// with $addToSet
const up = {
  $addToSet: { categories: [ '6073ac8f68f6971f3edfc898', '6073ac8f68f888f3edfc111' ] },
  ...update
}

// with $addToSet and $each
const up = {
  $addToSet: { categories: { $each: [ '6073ac8f68f6971f3edfc898', '6073ac8f68f888f3edfc111' ] } },
  ...update
}


const post = await strapi.query('post').model
  .findOneAndUpdate({_id: 'blahblahblah'}, up, { new: true })
  .populate({
    path: 'categories',
    select: 'name'
  });

the above uses findOneAndUpdate but I have also tried using update / updateOne

None of the above worked, anyone has any idea what I have gone wrong?

Thanks in advance for any suggestions.

Source: Ask Javascript Questions

LEAVE A COMMENT