MongoDB查询数组位置运算符奇怪的行为

时间:2017-10-04 13:06:49

标签: node.js mongodb mongoose

我有mongoose的这个架构:

var schema = mongoose.Schema({
    game: Number,
    words: Number,
    players: [{
        name: String,
        wordPercentage: Number,
        totalWords: Number
    }]
});

我想做的是通过wordPercentage: (totalWords / totalGameWords) * 100

更新数组中每个索引的wordPercentage

我尝试过:db.gamedatas.findOneAndUpdate({game: 1}, {$set: { 'players.$.wordPercentage': (('players.$.totalWords' / totalGameWords) * 100 } });totalGameWords是一个局部变量。

但我收到此错误:The positional operator did not find the match needed from the query. Unexpanded update: players.$.wordPercentage

我厌倦了使用players.$[].wordPercentage但我又收到了另一个错误:cannot use the part (players of players.$[].wordPercentage)

使用players.1.wordPercentage就像魅力一样,但这不是我悲伤的原因。

1 个答案:

答案 0 :(得分:1)

试试这个:

schema.findOne({game : 1})
            .exec()
            .then(doc => {
                doc.players.forEach((player,i,players)=>{
                   players[i].wordPercentage = (players[i].totalWords / players[i].totalGameWords) * 100
                })
                doc.save();
                return doc;
            })
            .catch(err=>{
               console.log(err)
            })