0
votes

I am a novice in express+mongo+backbone. I am fetching data from mongodb via backbone collection.fetch(); in return I am getting the data but as you can see below .length and models array is showing as 0 which is wrong. Because if I drill down, I can see all my documents/models. What am I doing wrong here? Below is my code at client side - backbone

var API = {
    getContactEntities: function () {
        var contacts = new Entities.ContactCollection();
        console.log("fetching data from database");
        contacts.fetch();
        console.log(contacts);
        if (contacts.length === 0) {
            // if we don't have any contacts yet, create some for convenience
            //return initializeContacts();
        }
        return contacts;
    }
};

Below is my code on server - express.js which is responding to fetch on url "/contacts"

//app.get('/contacts', appointments.allContacts);
exports.allContacts = function (req, res) {
    db1.db.users.find({}, function(err, appointments) {
        if (err) { res.json(err); }
        res.json(appointments);
    });
};
--------------------------------------------------------------------------------------
child {length: 0, models: Array[0], _byId: Object, constructor: function, url: "contacts"…}
_byId: Object
c5: child
c6: child
c7: child
c8: child
__proto__: Object
_events: Object
_listenerId: "l4"
length: 4
models: Array[4]
0: child
_changing: false
_events: Object
_pending: false
_previousAttributes: Object
attributes: Object
_id: "52604e58d40340638c5e4b45"
address: Object
firstName: "Alen"
lastLogin: ""
lastName: "Wilkins"
phoneNumber: "555-0184"
pwd: ""
userId: "1"
userName: "[email protected]"
userStatus: "active"
userType: "admin"
__proto__: Object
changed: Object
cid: "c5"
collection: child
__proto__: Surrogate
1: child
2: child
3: child
length: 4
__proto__: Array[0]
__proto__: Surrogate

Could any of you explain whats wrong?

To completely rule out the behavior of MongoDB, I did just pass a json object as resonse but still the result is the same!!! so it has to be something with express or backbone

res.json(
        [
            { _id: 1, firstName: 'Alice_db', lastName: 'Arten',
                phoneNumber: '555-0184' },
            { _id: 2, firstName: 'Bob_db', lastName: 'Brigham',
                phoneNumber: '555-0163' },
            { _id: 3, firstName: 'Charlie_db', lastName: 'Campbell',
                phoneNumber: '555-0129' }
        ]
    )

Many Thanks in advance.

BR, Chidan

1
Post a code snippet, please. Is your server JSON response just a raw array of objects (not a wrapper object)?Peter Lyons
Are you accounting for the fact that fetch is an AJAX call? Are you sure that you're waiting for the server to respond before trying to look at the data?mu is too short
Hi Mu, Peter, I have added the code snippetChidu Murthy
Hi Mu, I artificially introduced a delay of 2 secs, but the result is stil the same :( setTimeout(function () { contacts.fetch(); }, 2000);Chidu Murthy
@PeterLyons, any suggestions?Chidu Murthy

1 Answers

0
votes

Most things you posted look OK. The setTimeout you did missed the point:

contacts.fetch();
//fetch is asynchronous. contacts is ALWAYS still going to be empty here
console.log(contacts);
contacts.on('sync', function () {
  //look, the 'sync' event has fired meaning the data is actually here now!
  console.log(contacts); 
});