无法将新对象插入嵌入式阵列

时间:2016-03-06 22:10:07

标签: mongodb meteor

我是Mongodb的新手,我一直在努力让嵌入式阵列工作。在插入时,我能够毫无问题地插入数组的第一个元素。但是,当我更新时,它会不断抛出错误,即' 0不是对象,这对于错误消息是模糊的。我该怎么做才能解决它?

以下是我的架构:

FightCards.schema = new SimpleSchema({
    event_id: {
        type: Number
    },
    player_id: {
        type: String
    },
    fighters: {
        type: [Object]
    },
    'fighters.$.id': {
        type: Number
    },
    'fighters.$.name': {
        type: String
    },
    'fighters.$.salary': {
        type: Number
    }
});

以下是有问题的代码:

 if(FightCards.find({}).count() == 0) {
            FightCards.insert(
                {event_id: this.props.event_id, player_id: Meteor.userId(), fighters: [ {id: fighter.id, name: fighter.first_name + " " + fighter.last_name, salary: salary} ]}, 
                (err, res) => {
                    if(err) console.log(err);
                }
            );
} else {
            FightCards.update({event_id: this.props.event_id, player_id: Meteor.userId()},
                { $push: { fighters: [{id: fighter.id, name: fighter.first_name + " " + fighter.last_name, salary: salary}]}},
                (err, res) => {
                    if(err) console.log(err);
                }
            );
}

1 个答案:

答案 0 :(得分:2)

您正在尝试将数组推送到数组上,您只需要推送该元素。变化:

{ $push: { fighters: [{ id: fighter.id, name: fighter.first_name + " " +
  fighter.last_name, salary: salary }]}},

{ $push: { fighters: { id: fighter.id, name: fighter.first_name + " " +
  fighter.last_name, salary: salary }}},

此外,您可以通过设置查询来简化代码,因为$push将创建数组(如果它尚不存在):

let query = {
  event_id: this.props.event_id,
  player_id: Meteor.userId()},
  { $push: { fighters: {
    id: fighter.id,
    name: fighter.first_name + " " + fighter.last_name,
    salary: salary
  }}
};

if( FightCards.find({}).count() ) {
  FightCards.update(query,(err, res) => {
    if(err) console.log(err);
  });
} else {
  FightCards.insert(query,(err, res) => {
    if(err) console.log(err);
  });
}