Trouble Parsing JSON Data

Hi @Joewangatang and welcome in the MongoDB Community :muscle: !

I think what you are trying to do here is to set all the values from your value field into your document in MongoDB with _id == "the value from objectID field".

If that is correct then I think you can get away from this with a simple function like this:

exports = function(payload, response) {
    const body = EJSON.parse(payload.body.text());
    const id = BSON.ObjectId(body.objectID);
    const coll = context.services.get("mongodb-atlas").db("test").collection("coll");
    return coll.updateOne({'_id': id},{'$set': body.value});
};

Here is my test.

I inserted this doc:

MongoDB Enterprise Free-shard-0:PRIMARY> db.coll.insert({name:"Maxime"})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise Free-shard-0:PRIMARY> db.coll.findOne()
{ "_id" : ObjectId("5ff7b41bc922979b2f673bcf"), "name" : "Maxime" }

Then I sent my cURL command:

curl \
-H "Content-Type: application/json" \
-d '{"objectID":"5ff7b41bc922979b2f673bcf", "value": {"name":"Maxime Beugnet", "age": 32}}' \
https://eu-west-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/community-test-oubdb/service/HTTP/incoming_webhook/test

And then my document was like this:

MongoDB Enterprise Free-shard-0:PRIMARY> db.coll.findOne()
{
	"_id" : ObjectId("5ff7b41bc922979b2f673bcf"),
	"name" : "Maxime Beugnet",
	"age" : 32
}

As you can see above, my field name was updated and the new field age was added correctly.

I hope I understood what you were trying to do correctly.

Cheers,
Maxime.

1 Like