Update array inside of Mongo document doesn't work

Viewed 80

I have a user's collection, each user has a subscription array of objects. I want to add another subscription to that array. I'm getting the new subscription, updating it with findByIdAndUpdate, but it doesn't add the new subscription, however it shows that the document was updated. I tried several approaches but nothing worked well. Here is the last approach:

...
  const { user_id } = req.params;
  const subscription = req.body; // Getting subscription

  const user = await UserModel.findById(user_id).lean().exec(); // Getting user by id
  const { push_subscriptions } = user; // Getting subscribtions with destructuring
  const updated_subs = [...push_subscriptions, subscription];

  // Getting user another time and updating the push_subscriptions array
  const updated_user = await UserModel.findByIdAndUpdate(user_id, 
    {push_subscriptions: updated_subs},
    { new: true }
  ).exec();
...

Here are the logs of request body and params

// body
{
  endpoint: 'https://fcm.googleapis.com/fcm/send/cQ6wlRJ8t-s:APA91bEjqdLMzQLsroJ7zHzdjrzoshdPD8IJy_iIeRa8qV_Yjt6N1jeMUtyMq73wSn9JJT-4WXr_8uwHXttj-XFxHPCPAOqgN7zALsmf_BeIRZowRBTRHf9YH8v3AlcaZXWAIQ0qJNdn',
  expirationTime: null,
  keys: {
    p256dh: 'BBPC5h1QnBMPKMfPacgJu_2RFT7LAejyINh3CvP4pamkrlERr06YpRlSb7RbTUOn6MYW4adG93KfdEWXz68F9iQ',
    auth: 'Zl3iaOdBvihXG2QVOb26IQ'
  }
}
//params
{ user_id: '5fedc679f414663c693cf549' }

User schema, push_subscriptions part:

  push_subscriptions: {
    type: Array,
  },
1 Answers

Your query looks good, you can do single query using $push instead of doing manual process,

const { user_id } = req.params;
const subscription = req.body; 
const updated_user = await UserModel.findByIdAndUpdate(user_id, 
    { 
        $push: {
            push_subscriptions: subscription
        },
    { new: true }
).exec();
Related