我尝试了许多其他查询来解决这个问题,但都没有奏效,我希望有人能解决这个问题. 解决方案 在您的查询中,您使用 位置运算符($ 符号)通过 _id 本地化一个特定视频,然后您想要推送要报告的一项.问题在于 MongoDB 不知道您要更新哪个视频,因为您指定的路径 (seasons.episodes.videos.$.reports) 包含另外两个数组(seasons 和剧集).如文档所述,您不能多次使用此运算符位置$运算符不能用于遍历多个数组的查询,例如遍历嵌套在其他数组中的数组的查询,因为$占位符的替换是单个值此限制使您的情况复杂化.您仍然可以更新您的报告,但您需要知道外部数组的确切索引.因此,以下更新将是工作示例:db.movi​​es.update({'seasons.episodes.videos._id': data._id}, {$push: {'seasons.0.episodes.0.videos.$.reports': data.细节}})或者,您可以在 node.js 中更新本文档的大部分内容,或者在牢记技术限制的情况下重新考虑您的架构设计.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. 解决方案 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 valueThis 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. 这篇关于将元素推入嵌套数组 mongoose nodejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-14 03:50