0

I'm trying to push new object in deeply nested array sessions. How to push new data into such arrays? My Mongoose Schema is:

{
  month: String,
  sessionsCount: Number,
  dates: [{

    day: String,
    sessionsCount: Number,
    activeUsers: [{

      userId: String,
      userName: String,
      userEmail: String,
      lastActivityDate: Date,

      sessions: [{

        // some fields

      }]     

    }]

  }]
}

Query to update:

let query = { 
  "month": date.month, 
  "dates.day": date.day,
  "dates.activeUsers.userId": req.body.userId
};

let updateOptions = {
  $push: {"dates.activeUsers.sessions": data.dates.activeUsers.sessions}
}

Telemetry.update(query, updateOptions).then(session => res.json(session)).catch(error => res.json(error));

Error:

{
    "name": "MongoError",
    "message": "cannot use the part (dates of dates.activeUsers.sessions) to traverse the element ({dates: [ { day: \"22nd Jan\", _id: ObjectId('59520b5702bf00dc3482ceaf'), activeUsers: [ { userId: \"58f13c41114a70384a877b2e\", userName: \"Joel\", userEmail: \"jwasinger@thengan.com\", lastActivityDate: new Date(1485089983421), _id: ObjectId('59520b5702bf00dc3482ceb0'), sessions: [ { sessionStartDate: new Date(1496988833666), calendarShowChanged: 0, navigationDateChanged: 0, viewChanged: 0, orientationChanged: 0, multiboardChanged: 0, settingsChanged: 0, cardsRefreshed: 0, cardCreated: 0, cardRemoved: 0, cardEdited: 22, cardDropped: 0, cardOpened: 0, shortcutActivated: 0, sessionId: \"2\", appType: \"chromeExtension\", _id: ObjectId('59520b5702bf00dc3482ceb1') } ] } ], sessionsCount: 1 } ]})"
}

The same problem with updating data in nested arrays

  • 2
    use positional operator '$', https://docs.mongodb.com/manual/reference/operator/update/positional/ – Ankit Kumar Jun 27 '17 at 08:39
  • Don't nest arrays. The [positional `$` operator documentation](https://docs.mongodb.com/manual/reference/operator/update/positional/) will tell you that it can match **only** in the "outmost" array. Whilst you can manually identify by index, the best thing to do here is simply "flatten" your structure. In this case, do not "nest" the "month" and "day", and simply make that data attributes of the same array entries. Then no problems. Once you learn the correct syntax that is. – Neil Lunn Jun 27 '17 at 08:41
  • I was facing same kind of problem today, and after lot of exploring on google/stackoverflow/github, I figured `arrayFilters` are the best solution to this problem. Which would work with mongo 3.6 and above. This link finally saved my day: https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html – THE INN-VISIBLE Mar 01 '19 at 14:31

0 Answers0