如何将玩家姓名和分数加入数据库

时间:2017-11-30 20:58:12

标签: javascript mongodb angular post seed

我正在构建一个记分牌网络应用程序,其角度可以发布玩家的名字和分数。我希望在应用程序运行之前播种数据,但是如果它在数组中列为字符串,我只能播种它们的名称:

var players = [
  'Bob',
  'Tom',
  'Mark'
];

我想使用数组中的对象来播放玩家的名字和得分,如下所示:

var players = [
  {"name": "Mary", "score": 9},
  {"name": "Barry", "score": 16},
  {"name": "Harry", "score": 12}
];

下面是我的功能,即在上面列出的对象中发布玩家的名字和得分'0'而不是他们的得分。我只希望新玩家获得'0'的分数。

seed.js

players.forEach(function (player, index) {
  Player.find({ 'name': player},
   function(err, players) {
    if (!err && !players.length) {
      Player.create({ score: 0, name: player });
    }
  });
});

This is the model that I created in MongoDB for the player:

player.js

'use strict';

var mongoose = require('mongoose');

var playerSchema = new mongoose.Schema({
  name: String,
  score: Number
});

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

module.exports = model;

这是播放器的html:

player.html

<div class="item" ng-repeat="player in players | orderBy: 'player.score' ">
  <label ng-hide="editing" ng-click="editing=true">{{player.name}}</label>
  <input ng-show="editing" ng-blur="editing = false" class="editing-label" type="text" ng-model="player.name" ng-change="player.edited = true"/>
  <div class="actions">
    <button ng-model="player.score" min="0" ng-click="player.score = player.score - 1" type="number" >-</button>
    <label ng-model="player.score" placeholder="0" class="editing-label">{{player.score}}</label>
    <button ng-model="player.score" min="0" ng-click="player.score = player.score + 1" type="number">+</button>
    <a href="" ng-click="savePlayers()">Save</a>
    <a href="" class="delete" ng-click="deletePlayer(player, $index)">Delete</a>
  </div>
</div>

以下是我的应用目前的展示方式:

Current

以下是我希望我的应用看起来的图片:

Desired

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

当您播种时,通常您会希望事先删除数据库中的数据,因此数据库中不会有任何播放器 - 这意味着您不必担心它们是否已经存在当你播种。

如果是这种情况,您可以像这样编写seed.js,只需从数组中创建每个播放器:

Player.remove({}, function(err) {
  //this will remove all the players from your table
  if(err) console.error(err);
  else {
    players.forEach(function (player) {
      //player is an object with both the name and score
      Player.create(player, function(err, createdPlayer) {
        if(err) console.error(err);
        else console.log('player was created!', createdPlayer);
      });
    });
  }
}) 

如果您希望每次重新播放时都不删除条目,则可以使用已有的代码,但如果在数据库中找不到播放器,则可以使用阵列中的播放器对象创建它:

players.forEach(function (player) {
  Player.find({name: player.name },
   function(err, players) {
    if (!err && !players.length) {
      Player.create(player, function(err) {
        if(err) console.error(err); //always handle your errors, just in case!
      });
    }
  });
});