这是我的任务:
这是我的实际代码:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var gameCounter = new Schema({
counter: [Number]
});
module.exports = mongoose.model('GameCounter', gameCounter);
这是我的mongo定义。
这是我的router.js文件:
router.get('/newgame',function(req, res){
GameCounter.find(function(err, games){
if(err)
res.send(err);
var setGame = new GameCounter();
setGame.counter = //and here i need to add +1
setGame.save();
res.json({ success: true, message: 'new game has counted', gamesplayed: games });
});
});
有人对我有点帮助吗?谢谢:))
答案 0 :(得分:1)
你的代码应该是这样的:
架构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var gameCounter = new Schema({
counter: Number
});
和节点代码:
router.get('/newgame', function(req, res) {
GameCounter.update({}, {
$inc: {
counter: 1
}
}, {
upsert: true
}, function(err) {
if (err) {
cb(err);
res.send(err);
} else {
res.json({
success: true,
message: 'new game has counted',
gamesplayed: games
});
}
});
});
更新: 在您的代码风格中,您可以执行以下操作:
router.get('/newgame', function(req, res) {
GameCounter.findOne(function(err, games) {
if (err) {
res.send(err);
} else if (games) {
games.counter++;
games.save((err, new_data) => {
if (err) {
res.send(err);
} else {
res.json({
success: true,
message: 'new game has counted',
gamesplayed: new_data.counter
});
}
});
}
});
});