I am trying to access property values of a mongoDB Atlas document within a mongoDB Realm HTTP function.
The document within the mongoDB collection looks like this:
{
"_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"
}
}
This is written in 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
However, the output looks like this when I run it:
> result (JavaScript):
EJSON.parse('{"$undefined":true}')
I'm looking for it to return the value of the stars property. Which in this case is 3.
I have tried calling the property value with landlord["stars"]
but I get the same response. When I return the typeof
the landlord document it says that it is indeed an object. However for whatever reason when I try to access the property values it returns as undefined.
Found the answer, needed to make it an asynchronous function. This now works
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