【问题标题】:Getting undefined values when I try to call property of object当我尝试调用对象的属性时获取未定义的值
【发布时间】:2021-07-02 16:32:44
【问题描述】:

我正在尝试在 mongoDB Realm HTTP 函数中访问 mongoDB Atlas 文档的属性值。

mongoDB 集合中的文档如下所示:

{
  "_id": {
    "$oid": "60dd5a9da81cb4304a8992fe"
  },
  "name": "testName",
  "reviews": [
    {
      "date": {
        "$date": {
          "$numberLong": "1624924800000"
        }
      },
      "stars": {
        "$numberInt": "1"
      },
      "review": "Test"
    },
    {
      "date": {
        "$date": {
          "$numberLong": "1625183486238"
        }
      },
      "stars": {
        "$numberInt": "3"
      },
      "review": "testReview"
    }
  ],
  "stars": {
    "$numberDouble": "2.0"
  }
}

这是用 MongoDB Realm 编写的。

exports = function(payload, response) {
    const collection = context.services.get("mongodb-atlas").db("info").collection("landlords"); // get landlords collection
    const query = {"_id":new BSON.ObjectId(payload.query._id)}; // set up query for search
    const landlord = collection.findOne(query); // finds object with corresponding id
    return landlord.stars; // should return the stars value in the object

但是,当我运行它时,输出看起来像这样:

> result (JavaScript): 
EJSON.parse('{"$undefined":true}')

我正在寻找它来返回 stars 属性的值。在这种情况下是 3。

我尝试使用landlord["stars"] 调用属性值,但得到相同的响应。当我返回typeof 房东文件时,它说它确实是一个对象。但是,无论出于何种原因,当我尝试访问它返回为未定义的属性值时。

【问题讨论】:

    标签: javascript node.js mongodb mongodb-realm


    【解决方案1】:

    找到了答案,需要将其设为异步函数。这现在有效

    exports = async function(payload, response) {
        const collection = context.services.get("mongodb-atlas").db("info").collection("landlords"); // get landlords collection
        const query = {"_id":new BSON.ObjectId(payload.query._id)}; // set up query for search
        const landlord = await collection.findOne(query); // finds object with corresponding id
        return landlord.stars; // returns the stars value in the object
    

    【讨论】:

    • 我在尝试调用“new BSON.ObjectId()”时得到一个值未定义
    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多