问题
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