Javascript 如何在mongoDB对象中指定默认值并增加特定值
我试图增加对象中的一个值,如果集合中还不存在文档,则为其他对象提供默认值Javascript 如何在mongoDB对象中指定默认值并增加特定值,javascript,mongodb,Javascript,Mongodb,我试图增加对象中的一个值,如果集合中还不存在文档,则为其他对象提供默认值 // 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.game
// 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。
您知道如何在同一查询中也提供默认值吗?您是否使用Mongoose?否,“mongodb”:“^3.1.1”您是否为
TotalVows
集合准备了任何验证或架构?否没有为此创建验证或架构,我可以使用架构提供默认值吗?为了指定默认值,您必须创建某种模式。直到v3.6()才在MongoDB中引入架构验证。此解决方案应该为您指明正确的方向:您是否使用Mongoose?否,“MongoDB”:“^3.1.1”您是否为totalVotes
集合准备了任何验证或架构?否没有为此创建验证或架构,我可以使用模式给出默认值吗?为了指定默认值,您必须创建某种模式。直到v3.6()才在MongoDB中引入架构验证。此解决方案应该为您指明正确的方向: