em-wilson / book-node-mongodb-backbone

Example source code accompanying O'Reilly's "Building Node Applications with MongoDB and Backbone" by Mike Wilson

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

addContact Function in Account (Node) model, malfunctioning as is

cralvarado opened this issue · comments

in the addContact() function in the Account model (server side), the book's example code on page 104 ex. 8-13 reads as so:

var addContact = function( account, addcontact) { 
    contact = { 
        name: addcontact.name, 
        accountId: addcontact._id, 
        added: new Date(), 
        updated: new Date() 
    }; 
    account.contacts.push( contact); 

    account.save( function (err) { 
        if (err) { 
            console.log(' Error saving account: ' + err); 
        } 
    }); 
};

However, when the contact gets pushed to contacts the name attribute seems to be dropped. I am not sure if this is a node version issue but this of course causes issues when the view is rendered for the model because the name element does not exist (as it is not being persisted to the db).

I changed my code to explicitly reference first and last like so:

var addContact = function( account, addcontact) { 
    contact = { 
        name: {
            first: addcontact.name.first,
            last: addcontact.name.last
        }, 
        accountId: addcontact._id, 
        added: new Date(), 
        updated: new Date() 
    }; 
    account.contacts.push( contact); 

    account.save( function (err) { 
        if (err) { 
            console.log(' Error saving account: ' + err); 
        } 
    }); 
};

This solved the issue for me.

Just went through this as well, used the same solution.

Of course I find this after struggling for an hour on it! I had the same problem, and came to the same conclusion. Is this due to a version issue of some sort?

You should also delete Mongo corrupt documents : db.accounts.remove({email:''}).
thanks cralvarado