简体   繁体   English

更新 Mongoose 中的文档(更新特定索引处的数组属性)

[英]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.我目前正在练习我的 node.js 技能,我正在用户的个人资料页面上制作 top10 电影列表。 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).但是,这不起作用,数组仍然为空(尽管我能够将“picked”属性更改为 true)。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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