【问题标题】:How do I access properties on this object?如何访问此对象的属性?
【发布时间】:2014-03-21 19:25:08
【问题描述】:

我在 node.js 和 socket.io 工作,基本上我侦听一个套接字 disconnect 事件并调用一个方法。 app.update()

socket.on('disconnect', function (data) {
    app.update();
});

// This is in another file, and the id is static, but I am more concered with the
// messages object that is passed through.
update: function() {
    models.Message.find({_id: "532c8d9ce889ed4c21538630"}, function(err, messages) {
        console.log(messages)
    });
}

这就是messages 对象的样子

[ { username: 'Marcus',                                         
    connected: true,                                            
    _id: 532c8d9ce889ed4c21538630,                              
    __v: 0 } ]

我不确定如何访问带有括号的对象,但基本上我想更新该对象,以便将connected 设置为 false。

我试过messages['connected']

【问题讨论】:

    标签: javascript node.js mongodb object


    【解决方案1】:

    你有一个对象数组。所以你需要访问数组的第一个元素,然后是'connected'属性。这样做:

    messages[0].connected = false;
    

    【讨论】:

    • 感谢您提供一个将连接更改为错误、完美的示例。
    【解决方案2】:

    messages 可能包含多个结果,因此您有一个数组。

    实际上messages 将始终是一个数组,因为您使用的是find,它需要多个结果。如果你改用findOne,它就不是一个数组而是一个文档。

    你应该试试例如..messages[0].username

    【讨论】:

    • 啊,谢谢,我记得在 mongodb 文档中看到了 findOne。我忘记了。而且我不敢相信我会这么笨,括号几乎总是代表一个数组。我只是很困惑为什么它返回一个没有意义的数组。现在可以了!谢谢!
    • 对了,请务必将mongodb和nodejs作为标签添加到这篇文章中
    【解决方案3】:

    如果你想更新它们中的每一个:

    messages.forEach(function(message) {
        message.connected = false;
    });
    

    【讨论】:

      猜你喜欢
      • 2013-06-19
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 2011-02-17
      • 2019-06-02
      • 2020-02-11
      相关资源
      最近更新 更多