【问题标题】:Mongoose returns Mongo object, but can't access property on itMongoose 返回 Mongo 对象,但无法访问其上的属性
【发布时间】:2015-08-02 17:17:58
【问题描述】:

在我简单的 Node/Mongo/Mongoose 设置中,我有一个函数调用服务器以查看我当前使用的最高 ID 是多少,并返回下一个 ID。此函数将创建新Game 的功能作为回调。

奇怪: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);
        }
    });
};

【问题讨论】:

    标签: javascript json node.js mongoose


    【解决方案1】:

    我推荐你使用 autoincrement mongoose 插件,类似这样的

    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...
       })
    }
    

    执行这段代码后,你应该有这样的东西:

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

    【讨论】:

    • 这太棒了,我没听说过。它工作得很好。谢谢!
    猜你喜欢
    • 2016-07-22
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多