简体   繁体   English

JavaScript Object.hasOwnProperty()问题

[英]JavaScript Object.hasOwnProperty() issue

This is a document from mongodb: 这是来自mongodb的文档:

{
    "_id" : ObjectId("5c11827eec69860e24519415"),
    "cardNumber" : "4519021475877785",
    "accounts" : [ 
        {        
            "_id" : ObjectId("5c10975d58fdf013e803e5da"),
            "currency" : "CAD"
        }
    ]
}

I get the account from it: account = data.accounts[0] . 我从中获得帐户: account = data.accounts[0]

I can get the value of currency of this account: currency = account.currency 我可以获得该帐户的currency值: currency = account.currency

In my opinion, I think the account in JavaScript is an object. 我认为,JavaScript中的帐户是一个对象。

So, account.hasOwnProperty('currency') should be true . 因此, account.hasOwnProperty('currency')应该为true

But it is false when I run my code.... 但是当我运行代码时,它是false

Anyone has idea? 有人知道吗?

The object Mongoose gives you as the result of your query is not a plain-old JS object. Mongoose给您的对象是您的查询结果,而不是普通的JS对象。 It is a Document object (that class is defined in Mongoose) that holds the data somewhere else (possibly in its prototype chain), which is why hasOwnProperty returns false. 这是一个Document对象(该类在Mongoose中定义),将数据保存在其他地方(可能在其原型链中),这就是hasOwnProperty返回false的原因。

If you want to get your hands on an object that does contain the data fields as own properties, you can call the toObject() method of the Document object. 如果您想使用一个确实包含数据字段作为其自身属性的对象,则可以调用Document对象的toObject()方法。 Docs here 文件在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM