当我尝试调用对象的 属性 时获取未定义的值

Getting undefined values when I try to call property of object

我正在尝试在 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领域写的。

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}')

我正在寻找return星的价值属性。在这种情况下是 3.

我尝试用 landlord["stars"] 调用 属性 值,但我得到了相同的响应。当我return typeof 楼主的文档里面说确实是一个对象。但是,无论出于何种原因,当我尝试访问 属性 值时,它 return 未定义。

找到答案,需要使其成为异步函数。这现在有效

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