我有mongoose的这个架构:
var schema = mongoose.Schema({
game: Number,
words: Number,
players: [{
name: String,
wordPercentage: Number,
totalWords: Number
}]
});
我想做的是通过wordPercentage: (totalWords / totalGameWords) * 100
我尝试过: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
就像魅力一样,但这不是我悲伤的原因。
答案 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)
})