Home > Enterprise >  MongoDB with mongoose: how to push an object to a nested array of documents?
MongoDB with mongoose: how to push an object to a nested array of documents?

Time:01-17

I have my MongoDB, following this Schema:

   const userSchema = new Schema(
  {
   (...),
    therapy_records: {
     (...),
      daily_record: [
        {
          therapy_day: '',
          date: '',
          consumed: '',
          limit: '',
          goal: '',
          morning_timer: '',
        },
      ],          
  },    
)

I am trying to addAsNewItemIfArrayExists/createIfNotExists pushing a new daily_record object every time, but my code below is just adding and object with only an "_id" without records if daily_record does not exists. It does nothing when it exists.

Can anyone tell which would be the right way to do it? Thx!

const user = await User.findByIdAndUpdate(
  userId,
  {
    therapy_records: {
     (..),
     daily_record: {
          $push: [
            {
              therapy_day: anyNumber,
              date: anyDate,
              consumed: anyNumber,
              limit: anyNumber,
              goal: anyNumber,
              morning_timer: anyNumber,
            },
          ],
        },
      
     (...),
    },
  },
  { new: true, upsert: true }
)

CodePudding user response:

You need to use:

const user = await User.findByIdAndUpdate(
  userId,
  {
      $push: {
        'therapy_records.daily_record': {
          therapy_day: *anyNumber*,
          date: *anyNumber*,
          consumed: *anyNumber*,
          limit: *anyNumber*,
          goal: *anyNumber*,
          morning_timer: *anyNumber*,
        },
      },
  },
  { new: true, upsert: true }
)
  • Related