简体   繁体   English

无法使用Javascript从文档(MongoDB)更新数组

[英]Update Array from Document (MongoDB) in Javascript not Working

I've looking for an answer for like 5 five hours straight, hope somebody can help. 我一直在寻找5个连续五个小时的答案,希望有人能提供帮助。 I have a MongoDb collection results (I'm using mLab) which looks like this: 我有一个MongoDb收集结果 (我正在使用mLab),看起来像这样:

    {
    "user":"5818be9c74aaec1824c28626"
    "results":[{
             "game_id":14578,
             "level1":-1,
             "level2":-1,
             "level3":-1
         }, 
     { ....
     }],
         { "user":....
         }
     }

"user" is a MongoID I save in a previous part of the code, "results" is a record of scores. “用户”是我保存在代码前面的MongoID,“结果”是分数的记录。 When an user does a new score, I have to update the score of the corresponding level (I'm using NodeJS). 当用户进行新评分时,我必须更新相应级别的评分(我正在使用NodeJS)。 This is one of the things I've tried so far. 到目前为止,这是我尝试过的事情之一。

 app.get('/levelCompleted/:id/:time', function (request, response) {
 var id = request.params.id;
 var time = parseInt(request.params.time);
 var u= game.getUserById(id);
 var k = "results.$.level"+(u.level);
 //I build the key to update dinamycally
 dbM.collection("results").update(
    {user:id,
    "results.game_id":u.game_id
    //u has its own game_id
    },
    {$set: {k:time}}
);
...
response.send(...);

}); });

I've checked the content of every variable and parameter, tried also using $elemMatch and dot notation, set upsert and multi, with no results. 我检查了每个变量和参数的内容,还尝试使用$ elemMatch和点表示法,设置upsert和multi,但没有结果。 I've used an identical command on mongo shell and it has work on the first try. 我在mongo shell上使用了相同的命令,并且在第一次尝试时就起作用了。

Update with Mongo Shell 用Mongo Shell更新

If someone could tell me what I'm doing wrong or point me in the right direction, it would be great. 如果有人可以告诉我我做错了什么或将我指向正确的方向,那将很棒。 Thanks 谢谢

When you use a MongoId as a field in a MongoDB, you can't just pass a string with the id to do the query, you have to identify that string as an ObjectId (Id type in Mongo). 当您将MongoId用作MongoDB中的字段时,不能仅传递带有ID的字符串来执行查询,您必须将该字符串标识为ObjectId (Mongo中的ID类型)。 Just add a new require in your node.js file. 只需在node.js文件中添加一个新的require

var ObjectID = require("mongodb").ObjectID;

And use the imported constructor in your update request. 并在更新请求中使用导入的构造函数。

dbM.collection("results").update(
    {user:ObjectID(id),...
    ...
    }

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

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