2015-05-21 63 views
1

在我簡單的Node/Mongo/Mongoose設置中,我有一個函數調用服務器來查看當前使用的最高ID是什麼,然後返回下一個ID。此功能將回調功能創建一個新的GameMongoose返回Mongo對象,但無法訪問它的屬性

奇怪:本logger.log因爲它出現下面輸出

result { _id: 555d83d5bb0d4e3c352d896f, gameId: 'NaN' } 

但是當我改變記錄器

logger.log("result", result.gameId); 

輸出是

result { _id: 555d83d5bb0d4e3c352d896f, gameId: 'NaN' } 

這是沒有意義的。顯然,財產在那裏!

這裏是我的代碼

var createGame = function(gameNickname, callback){ 
    nextGameId(function(nextId){ 

     var newgame = new models.Game({ 
      "gameId": Number(nextId), 
      "gameNickname": gameNickname 
     }); 
     newgame.save(function(result, game){ 
      callback(result + nextId); 
     }); 
    }); 


}; 
var nextGameId = function(callback){ 
    var games = models.Game.find({}, {gameId: 1}); 
    games.sort('-gameId').limit(1) //get the highest number roundId and add 1 to it 
    .exec(function (err, result) { 
     if (err) logger.log(err); 
     if (result === null){ 
      callback(0); 
     } 
     else{ 
      logger.log("result", result); 
      callback(result.gameId); 
     } 
    }); 
}; 

回答

1

我建議你使用自動增量貓鼬插件,財產以後這樣

var mongoose = require('mongoose'); 
var autoIncrement = require('mongoose-auto-increment'); 

var connection = mongoose.createConnection("mongodb://localhost/db"); 

autoIncrement.initialize(connection); 

var GameSchema = { 
    "gameId":  {type: Number}, 
    "gameNickname": {type: String} 
} 

GameSchema.plugin(autoIncrement.plugin, { model: 'Game', field: 'gameId' }); 

mongoose.model('Game', GameSchema); 

在這之後,你可以保存AUTOINC你的遊戲,例如:

var Game = mongoose.model('Game');

function createNewGame(nickname){ 
    return new Game({gameNickname: nickname}).save(function(err, res){ 
     console.log(res); 
     //some code... 
    }) 
} 

執行這個代碼,您應該somnthing這樣後:

{ 
    _id:   "555d83d5bb0d4e3c352d896f", 
    gameNickname: "nickname", 
    gameId:  1 
} 
+1

這是真棒我沒有聽說過這件事。它效果很好。謝謝! – CodyBugstein