Howdy,
I keep running into issues trying to make POST request to a custom HTTP endpoint that runs a function updateOne with upsert = true. Here is my function:
`
`
exports = function({query, headers, body}, response) {
const requestBody = JSON.parse(body);
const idQuery = { "id": requestBody.id };
const update = {
"$set": {
"id": requestBody.id,
"title": requestBody.title,
"img": requestBody.img,
"link": requestBody.link
}
};
const options = { "upsert": true };
const doc = context.services.get("mongodb-atlas").db("my-api").collection("my-collection");
doc.updateOne(idQuery, update, options)
.then(result => {
const { matchedCount, modifiedCount, upsertedId } = result;
if(upsertedId) {
console.log(`Document not found. Inserted a new document with _id: ${upsertedId}`);
} else {
console.log(`Successfully updated plug ${idQuery.id} : ${matchedCount} : ${modifiedCount}`);
}
// Add response handling here if needed
})
.catch(err => console.error(`Failed to upsert document: ${err}`));
};
When I send the request to my endpoint, I get a 400 error
“error”:“SyntaxError: invalid character ‘o’ looking for beginning of value”,
“error_code”:“FunctionExecutionError”
To rule some things out, when I add .text() to the end of body it tells me that .text() is not a function.
My function works in the code editor but thats not really the point. I’m using Axios to send the HTTP requests from my page. I have read through the documentation looking for anything but these errors are not very specific so it’s hard to pin down what the problem is.
Here is some test data I am using in the function editor:
`
`
let body = JSON.stringify({
id: 'test1',
title: 'test1',
img: 'test1',
link: 'test1'
});
let token = "my token"
const headers = {
'Content-Type': 'application/json',
'Access-Control-Request-Headers': '*',
'Authorization': 'Bearer ' + token,
};
exports({headers, body})
````
`
`