从Node API查询Mongo

时间:2016-08-31 04:19:01

标签: node.js mongodb mongoose

我有一个查询我的Mongo数据库的Node API。

我能够返回集合中的所有文档。现在,我想返回部分文件。

我的模型(即Player.js)看起来像这样:

var mongoose = require('mongoose');

// Create schema for players
var playerSchema = mongoose.Schema(
    {
        player_name:String,
        goals:Number,
        clubs:
        {
            club_name:String,
            season:String
        }
    }
);

var Player = module.exports = mongoose.model('Player',playerSchema);

// get all players
module.exports.getPlayers = function(callback, limit){
    Player.find(callback).limit(limit);
};

我的应用程序如下所示:

//...

app.get('/api/players',function(req,res){
    Player.getPlayers(function(err,players){
        if(err){
            throw err;
        }
        res.json(players);
    });
});

//...

我想查询我的玩家收藏中的所有文件,但是当我转到" ... / api / players / player_names"

时,只返回player_name

我认为添加下面的代码会起作用,但它不会......

这是我的模特:

// [previous code]

// get all player names
module.exports.getPlayerNames = function(callback,limit){
    Player.find(callback,player_name:1).limit(limit)
}

这在我的app.js上:

//...

app.get('api/players/player_names',function(req,res){
    Player.getPlayerNames(function(err,players){
        if(err){
            throw err;
        }
        res.json(players);
    });
});

//...

1 个答案:

答案 0 :(得分:0)

你可能想要这样的东西:

var mongoose = require('mongoose');

// Create schema for players
var playerSchema = mongoose.Schema(
    {
        player_name:String,
        goals:Number,
        clubs:
        {
            club_name:String,
            season:String
        }
    }
);

//Its most common to pass the callback last, as this is what others do
playerSchema.statics.getPlayers = function(limit, callback){
    this.find({})
    .select('player_name')
    .limit(limit)
    .exec(callback);
};

module.exports = mongoose.model('Player',playerSchema);

将返回[{_id: ObjectId, player_name: "player1"}, ...]之类的结果。

如果您只想返回一系列玩家名称:

var mongoose = require('mongoose');

// Create schema for players
var playerSchema = mongoose.Schema(
    {
        player_name:String,
        goals:Number,
        clubs:
        {
            club_name:String,
            season:String
        }
    }
);

//Its most common to pass the callback last, as this is what others do
playerSchema.statics.getPlayers = function(limit, callback){
    this.find({})
    .select('player_name')
    .limit(limit)
    .exec(function(err, docs) {
      if(err) return callback(err); //first argument should be reserved for passing any errors

      callback(null, docs.map(function(doc) {
        return doc.player_name;
      });
    });
};

module.exports = mongoose.model('Player',playerSchema);