0

I'm new to Mongodb and I've been having hell of a time trying to get embedded array working. On insert, I'm able to insert the first element of the array without a problem. However when I update, it keeps throwing an error that '0 is not an Object', which is vague for a error message. What can I do to fix it?

Here are my schema:

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

Here is the offending code:

 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 Answer 1

2

You're trying to push an array onto an array, you only need to push the element. Change:

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

to

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

Also you can simplify your code by setting up the query once since $push will create the array if it doesn't yet exist:

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);
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help, that fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.