我正在尝试增加对象中的一个值,而如果文档中不存在该文件,则为其他值提供默认值。
// the default should be 100 if the document is new :
_id : someObjectId,
gameId : someObjectId,
votes : {
a: 100,
b: 100,
c: 100
}
// my code :
function addVote(userVote) {
userVote.gameId = new ObjectId(userVote.gameId)
return mongoService.connect()
.then(db => {
const collection = db.collection('totalVotes');
return collection.findOneAndUpdate(
{ gameId: userVote.gameId },
{ $set: { gameId: userVote.gameId }, $inc: {["votes." + userVote.vote] : 1 } },
{ upsert:true , returnOriginal :false}
)
})
}
因此,我的代码现在创建的新文档的投票数为+ 1。 关于如何在同一查询中也提供默认值的任何想法吗?