Push element into nested array mongoose nodejs

青春壹個敷衍的年華 提交于 2020-07-18 07:26:04

问题


I am trying to push a new element into an array, I use mongoose on my express/nodejs based api. Here is the code for mongoose:

Serie.updateOne({'seasons.episodes.videos._id': data._id}, {$push: {'seasons.episodes.videos.$.reports': data.details}},
    function(err) {
      if (err) {
        res.status(500).send()
        console.log(err)
      }
      else res.status(200).send()
    })

as for my series models, it looks like this:

const serieSchema = new mongoose.Schema({
  name: {type: String, unique:true, index: true, text: true},
  customID: {type: Number, required: true, unique: true, index: true},
  featured: {type: Boolean, default: false, index: true},
  seasons: [{
    number: Number,
    episodes: [{number: Number, videos: [
      {
        _id: ObjectId,
        provider: String,
        reports: [{
          title: {type: String, required: true},
          description: String
        }],
        quality: {type: String, index: true, lowercase: true},
        language: {type: String, index: true, lowercase: true},
      }
      ]}]
  }],
});

When I execute my code, I get MongoDB error code 16837, which says "cannot use the part (seasons of seasons.episodes.videos.0.reports) to traverse the element (my element here on json)"

I've tried many other queries to solve this problem but none worked, I hope someone could figure this out.


回答1:


In your query you're using positional operator ($ sign) to localize one particular video by _id and then you want to push one item to reports.

The problem is that MongoDB doesn't know which video you're trying to update because the path you specified (seasons.episodes.videos.$.reports) contains two other arrays (seasons and episodes).

As documentation states you can't use this operator more than once

The positional $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ placeholder is a single value

This limitation complicates your situation. You can still update your reports but you need to know exact indexes of outer arrays. So following update would be working example:

db.movies.update({'seasons.episodes.videos._id': data._id}, {$push: {'seasons.0.episodes.0.videos.$.reports': data.details}})

Alternatively you can update bigger part of this document in node.js or rethink your schema design keeping in mind technology limitations.



来源:https://stackoverflow.com/questions/47511061/push-element-into-nested-array-mongoose-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!