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

标签 javascript node.js mongodb mongoose

我目前正在练习我的 Node.js 技能,并且正在用户的个人资料页面上制作前 10 名的电影列表。用户选择了十部电影,现在我想将这些电影保存在数据库的用户文档中。然而,这不起作用,数组仍然是空的(尽管我能够将“picked”属性更改为 true)。谁能告诉我为什么?这是服务器端的代码:

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);

关于javascript - 更新 Mongoose 中的文档(更新特定索引处的数组属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46836096/

相关文章:

javascript - 父宽度和高度区域中的轻量级可拖动锁

javascript - 从字符串转换时间时,setHours 不是函数

javascript - javascript 中 json 的循环问题

javascript - 如何在 Electron 应用程序中检测系统空闲并做一些事情

java - 带有 mongo atlas 的 Spring Boot 不起作用

php - 多个脚本共享的 MongoDB 服务器端聚合查询

javascript - 如何在 Mongoose 中只获得唯一值?

javascript - 为什么我的 React 组件不断重新渲染?

javascript - 如何以编程方式访问 NodeJS 异常文本

node.js - 如何在 tfs 构建管道中设置 Angular 7 的环境