Example: insert data into empty Mongo result set
In this example, we're going to detect that a query has returned an empty result set, and add an object to that result set.
We're going to assume the use of MSG packets, which is what most modern Mongo apps use.
Let's create a new JavaScript Response filter and set its Packet Types parameter to MSG.
We can then add the code:
let section = context.packet.getSection(0);
if ( ! section.isBody()) {
return;
}
let doc = section.getBody();
if (!doc.cursor || doc.cursor.ns !== 'mydb.mycollection') {
return;
}
let fb = doc.cursor.firstBatch;
if (fb && fb.length === 0) {
fb[0] = {message: 'There is no data in this collection'};
fb[1] = {message: 'Not even a little bit'};
}
A MongoDB response MSG packet always has at least one section, we check that it is of type BODY.
The body normally looks like:
{cursor: {firstBatch: [], id: 0, ns: "mydb.mycollection"}, ok: 1}
If the cursor.firstBatch array is empty, that's an empty result set, so we can simply add objects to it, and that's what the client will receive.
In the real world, you would probably use a duplex filter so that you can remember the last query and behave accordingly.