if语句socket io mongodb nodejs

时间:2018-12-07 08:54:05

标签: node.js mongodb mongoose socket.io

如果userallyenemyally不存在,然后不发送,该如何检查该代码。我应该先做if语句,然后再在没有用户盟友,没有敌人盟友或没有两者的情况下再做两个emits吗?

AllianceMember.findOne({username: user.username}).then((userally) => {
 AllianceMember.findOne({username: enemy.username}).then((enemyally) => {
      io.emit('fight-win', {
          username: user.username,
          useralliance: userally.ally_title,
          enemyalliance: enemyally.ally_title,
          enemyname: enemy.username,
});

1 个答案:

答案 0 :(得分:0)

假设它们是json对象,则可以将它们的默认值设置为空对象。

AllianceMember.findOne({username: user.username}).then((userally = {}) => {
 AllianceMember.findOne({username: enemy.username}).then((enemyally = {}) => {
      io.emit('fight-win', {
          username: user.username,
          useralliance: userally.ally_title,
          enemyalliance: enemyally.ally_title,
          enemyname: enemy.username,
});