0

I'm trying to keep a list of all the sites I'm working on right now, and I'm having issues using $push.

I've created a document with this:

accountData = {
    'accountid': account_id, 
    sites: {
        '001': 'example.com',
    }
};

db.accounts.insert(accountData);

This works great, I get:

{ accountid: 'AC654164545', 'sites.001': { '$exists': true } }

And I would like to add to the sites object. This is what I'm trying:

db.accounts.update( 

    {'accountid': account_id}, 
    { 
        $push: 
        { 
            sites: 
            { 
                '002': 'example2.com'
            } 
        } 
    }, 
    function(err,doc){
        console.log(err);
    }
);

The error that I get is:

err: 'The field \'sites\' must be an array but is of type Object in document

I don't want the document to be created with an array, as I know that if I did something like this when inserting:

    sites: {
        '002': 'example2.com',
        '003': 'example3.com',
        '004': 'example4.com',
    }

It would work just fine.

How do I use $push, or any other command, to add to the "sites" object without it being an array?

It can't be an array because I'm using the following to search for existing sites.

search['sites.' + site_id] = { $exists : true };
David
  • 2,094
  • 3
  • 30
  • 47
  • marked this as duplicate, I found a similar answer here: http://stackoverflow.com/questions/17288439/mongodb-how-to-insert-additional-object-into-object-collection – David May 31 '15 at 03:17

1 Answers1

0

Ok, I figured out what the problem was.

I wasn't thinking about the problem in the right context.

The error was correct in saying it needed to be an array, so I changed the "sites" object into an array like this when created (initial insert), so it's an array:

    accountData = {
        'accountid': account_id, 
        sites: [{'001': 'example.com'}]
    };

Then, by using the exact same code above to $push, it worked properly.

David
  • 2,094
  • 3
  • 30
  • 47