rare-sapphire•2y ago
MongoDB Function
I have this current function to receive results from mongodb: export default async function main(args) {
const {
dataSource,
database,
collection,
index,
queryVector,
apiKey,
URL
} = args.inputVars;
try {
const response = await fetch(URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Access-Control-Request-Headers': '*',
'api-key': apiKey,
'Accept': 'application/json'
},
body: JSON.stringify({
dataSource,
database,
collection,
pipeline: [
{
"$vectorSearch": {
"index": index,
"queryVector": queryVector,
"path": "plot_embedding",
"numCandidates": 100,
"limit": 5
}
},
{
"$project": {
"_id": 0,
"title": 1,
"plot": 1,
"score": { "$meta": "vectorSearchScore" }
}
}
]
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(
HTTP error! status: ${response.status}
);
}
return {
outputVars: {
documents: JSON.stringify(data.documents)
},
next: {
path: 'success',
},
};
} catch (error) {
return {
outputVars: {
error: error.message,
},
next: {
path: 'error',
},
};
}
}
When I run it i am getting this error: {"success":true,"latencyMS":574.2536602020264,"runtimeCommands":{"outputVars":{"error":"response.json is not a function"},"next":{"path":"error"}}}1 Reply
The error you're encountering,
{"success":true,"latencyMS":574.2536602020264,"runtimeCommands":{"outputVars":{"error":"response.json is not a function"},"next":{"path":"error"}}}
, is likely due to a misunderstanding of how the fetch API works within Voiceflow. In standard JavaScript, response.json()
is a method that parses the JSON content of a response. However, in Voiceflow's modified fetch API, the response body is directly accessible as a property rather than through a method. This means you don't need to call .json()
on the response object. Instead, you access the JSON response directly as a property.
Here are the key points to remember:
- Voiceflow's fetch API differs from the standard Fetch API by providing the response body directly as a property.
- To access the JSON response, you should not use .json()
as a method. Instead, access it as a property of the response object.
- This modification is designed to simplify working with network requests within Voiceflow functions.
For more detailed information on working with functions in Voiceflow, including making network requests, you can visit the following resources:
- Voiceflow Functions Documentation
- Using the Function Step