Occasional PreparedStatementFailureError thrown from cluster.query

I was using Node.js SDK 4.1 to run a simple query against a Couchbase 6.6 Community Server with the code below:

try {
        const cluster = this.cluster();

        let query = `SELECT meta(doc).id, * FROM \`${bucket}\` AS doc WHERE type = '${type}' and owner = '${uid}' `;

        if (start && typeof (start) === 'number') {
          query += ` AND time >= ${start} `;
        }

        if (stop && typeof (stop) === 'number') {
          query += ` AND time < ${stop} `;
        }

        query += ' ORDER BY time ';
        query += (asc && typeof (asc) === 'boolean' && asc === true) ? ' ASC ' : ' DESC';

        if (limit) query += ` LIMIT ${limit}`;
        if (offset) query += ` OFFSET ${offset}`;

        cluster.bucket(bucket);
        const { rows } = await cluster.query(query);
        res.send({
          data: rows,
        });
        logger.info(`Query ${query} executed successfully with ${rows.length} row(s) returned.`);
      } catch (error) {
        handleErr(error, res, logger);
      }

The result seems to be spotty; the query sometimes ran without any problem, but sometimes a PreparedStatementFailureError was thrown.

I tried to execute/prepare the same query manually in the Web console UI. It ran without a hitch.

Does anyone have similar problem?
Is there something to do with the timeout parameter?

Any tips will be highly appreciated.

After setting the logging level of the sdk to trace, I was able to track down the error to the followings:

[2022-06-10 10:15:33.546] [19,30] [trace] 1ms, [ea329560-a08e-4488-8be1-14cfc90195e9/22ed9019-1341-4407-585e-6b1f3b662a62] <10.1.5.20:8093> HTTP response: query, client_context_id="e3d8e3a6-3f39-45e0-6c40-cf9d3556337b", status=404, body={
"requestID": "a23f10e4-096a-4cd9-990c-1616be9376ae",
"errors": [{"code":4040,"msg":"No such prepared statement: 087ad4c0-a4dc-5571-a39e-f28aa0146af7"}],
"status": "fatal"
}

I therefore looked this up in the forum, and found this resolved issue.

As described in the issue above, I set the query option “adhoc” to true, and now the query seems to work fine consistently.