0

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 }
)
1
  • the example above, daily_record: [] is an array but I saw at your code is object daily_record: {} Commented Jan 16, 2023 at 9:40

1 Answer 1

1

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 }
)
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.