【问题标题】:MongoDB returns collection, but the the length property is showing as 0MongoDB 返回集合,但长度属性显示为 0
【发布时间】:2023-04-04 16:36:01
【问题描述】:

我是express+mongo+backbone的新手。 我正在通过骨干 collection.fetch() 从 mongodb 获取数据;作为回报,我正在获取数据,但正如您在下面看到的 .length 和模型数组显示为 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);
    });
};
-------------------------------------------------- ---------------------------------- 孩子{长度:0,模型:数组[0],_byId:对象,构造函数:函数,url:“联系人”…} _byId:对象 c5:孩子 c6:孩子 c7:孩子 c8: 孩子 __proto__: 对象 _events:对象 _listenerId:“l4” 长度:4 型号:数组[4] 0:孩子 _改变:假 _events:对象 _待定:假 _previousAttributes: 对象 属性:对象 _id:“52604e58d40340638c5e4b45” 地址:对象 名字:“艾伦” 上次登录: ”” 姓氏:“威尔金斯” 电话号码:“555-0184” 密码:“” 用户 ID:“1” 用户名:“chidu.murthy@gmail.com” 用户状态:“活动” 用户类型:“管理员” __proto__: 对象 改变:对象 cid:“c5” 收藏:孩子 __proto__: 代理 1:孩子 2:孩子 3:孩子 长度:4 __proto__: 数组[0] __proto__: 代理

谁能解释一下哪里错了?

为了完全排除 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,赤丹

【问题讨论】:

  • 请贴一个代码sn-p。您的服务器 JSON 响应是否只是对象的原始数组(而不是包装对象)?
  • 您是否考虑到 fetch 是一个 AJAX 调用这一事实?您确定在尝试查看数据之前等待服务器响应吗?
  • 嗨 Mu,Peter,我已经添加了代码 sn-p
  • 你好穆,我人为引入了2秒的延迟,但结果还是一样:( setTimeout(function () { contacts.fetch(); }, 2000);
  • @PeterLyons,有什么建议吗?

标签: mongodb backbone.js express


【解决方案1】:

您发布的大多数内容看起来都不错。 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); 
});

【讨论】:

    猜你喜欢
    • 2015-07-24
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    相关资源
    最近更新 更多