简体   繁体   中英

Update document in Mongoose (update array property at specific index)

I'm currently practicing my node.js skills and I am making a top10 movie list on a user's profile page. The user picked ten movies and now I want to save these movies in a user document in my database. This however, isn't working the array is still empty (I was able to change the 'picked' property to true though). Can anyone tell me why? Here is the code on the server side:

router.get('/updateTop10', function (req, res, next) {

    // the string that I want to add to the db array
    var movieElement = req.query.movieElement;

    // the specific index of the array (the position of the movie in the top10
   var index = req.query.index;

   // the user that is currently logged in
   var user = req.user;


   User.findOne({'username': user.username }, function (err, user) {
       // I am able to switch picked to true
       user.top10.picked = true;

       // However my array is still empty after I run the code
       user.top10.top10[index] = movieElement ;

       user.save();
       res.send("SUCCESS")
   } )
});

This is the structure of the user document:

这是用户文档的结构:

参考https://github.com/Automattic/mongoose/issues/2654 这样

 user.top10.top10.set(index, movieElement);

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