【问题标题】:MongoDB query array positional operator weird behaviorMongoDB查询数组位置运算符奇怪的行为
【发布时间】:2018-03-15 21:30:27
【问题描述】:

我有这个猫鼬模式:

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 就像一种魅力,但遗憾的是,这不是我所追求的。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案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)
                })
    

    【讨论】:

    • 可爱,我总是使用回调而不是承诺,我看到它们更好,谢谢!
    • 哦,我还做了一些小的修改以满足我的需要,将 schema.find 更改为 schema.findOne 并将 totalWords 更改为我的局部变量,而不是你如何拥有它,再次,谢谢! :)
    • 我也改了schema.find :D,再次,欢迎 :)
    猜你喜欢
    • 2011-09-10
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 2013-10-29
    • 2012-12-01
    • 2015-02-01
    相关资源
    最近更新 更多