简体   繁体   中英

$push into deeply nested array mongoose

my userSchema is as follows...

const userSchema = new mongoose.Schema({
    firstName: { type: String },
    lastName: { type: String },
    movies: [
        {
            name: String,
            duration: Number,
            actors: [{ name: String, age: Number }]
        }
    ],
});

In my NodeJS app with express I am trying to update my actors array to have another actor with value stroking from req.body.

I thought that I could do something like this...

await User.updateOne(
     {
          _id: req.user.id
          movies._id: req.params.id
     },
     {
          $push: { 'movies.actors': req.body }
     }
)

I thought this would push an actor into the specified movie req.params.id but does nothing instead.

Try using positional operator $ in this way:

db.collection.update({
  "_id": 1,
  "movies._id": 1
},
{
  "$push": {
    "movies.$.actors": req.body
  }
})

Note the only diference is the use of $ . But with positional operator you are saying mongo where push the new data.

As docs says:

The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.

So you can update the element movies.actors pushing new data without knowin the position of the element.

Example here

Try this:

await user.updateOne(
            {$and:[{_id: req.user.id},{movie.name: 'I am Legend'}]},
            {$set: { movies.actors:req.body}},
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM