【问题标题】:Push element into nested array mongoose nodejs将元素推送到嵌套数组猫鼬 nodejs
【发布时间】:2018-05-10 16:46:59
【问题描述】:

我正在尝试将一个新元素推送到一个数组中,我在基于 express/nodejs 的 api 上使用了 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()
    })

至于我的系列机型,是这样的:

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},
      }
      ]}]
  }],
});

当我执行我的代码时,我得到 MongoDB 错误代码 16837,它说“不能使用部分(seasons of seasons.episodes.videos.0.reports)来遍历元素(我的元素在 json 上)”

我已经尝试了许多其他查询来解决这个问题,但都没有成功,我希望有人能解决这个问题。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query mongoose-schema


    【解决方案1】:

    在您的查询中,您使用 位置运算符($ 符号)通过 _id 本地化一个特定视频,然后您希望将一项推送到报告中。

    问题在于 MongoDB 不知道您要更新哪个视频,因为您指定的路径 (seasons.episodes.videos.$.reports) 包含另外两个数组(seasons 和剧集)。

    如文档所述,您不能多次使用此运算符

    位置 $ 运算符不能用于遍历多个数组的查询,例如遍历嵌套在其他数组中的数组的查询,因为 $ 占位符的替换是单个值

    此限制会使您的情况复杂化。您仍然可以更新您的报告,但您需要知道外部数组的确切索引。所以以下更新将是工作示例:

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

    或者,您可以在 node.js 中更新本文档的大部分内容,或者重新考虑您的架构设计,同时牢记技术限制。

    【讨论】:

    • 谢谢,我应该事先做更多的研究,至少现在我知道了。
    猜你喜欢
    • 2018-09-19
    • 2016-06-05
    • 2022-01-03
    • 2019-10-13
    • 1970-01-01
    • 2021-07-26
    • 2022-01-25
    • 2019-11-15
    • 2019-03-22
    相关资源
    最近更新 更多