我是express + mongo + backbone的新手。 我通过backbone collection.fetch()从mongodb获取数据;作为回报我得到的数据,但正如你在下面看到的.length和models数组显示为0,这是错误的。因为如果我向下钻取,我可以看到我的所有文件/模型。 我在这做错了什么? 以下是我在客户端的代码 - 主干
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;
}
};
下面是我在服务器上的代码 - express.js响应了对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: "chidu.murthy@gmail.com" 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
你们任何人都可以解释什么是错的吗?
为了完全排除MongoDB的行为,我只是传递一个json对象作为共鸣,但结果仍然相同!所以它必须是表达或主干的东西
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' }
]
)
非常感谢提前。
BR,Chidan
答案 0 :(得分:0)
你发布的大多数内容都是ON。您setTimeout
错过了这一点:
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);
});