Database Error: MongoServerError: $search is not allowed with 'apiStrict: true' in API Version 1

Hello.
I am using Mongodb nodejs driver in my NextJS application. I have enable the stable API and used the options mentioned in the docs (strict: true specifically).

const client = new MongoClient(uri,
    {
        serverApi: {
            version: ServerApiVersion.v1,
            strict: true,
            deprecationErrors: true,
        }
});

Reading through the docs here, I see that if strict is set to true:

if you call a command that is not part of the declared API version, the driver raises an exception.

I am using $search pipeline in a query that I have:

const client = await clientPromise;
const db = client.db("dbName");
const collection = db.collection("collName");
const pipeline = [
  {
    $search: {
      index: "search index name that I created on atlas",
      text: {
        query: "query text",
        path: {
          wildcard: "*",
        },
        fuzzy: {},
      },
    },
  },
  {
    $limit: ITEMS_PER_PAGE,
  },
  {
    $skip: offset,
  },
  {
    $project: {
      score: { $meta: "searchScore" },
    },
  },
  {
    $sort: {
      score: -1,
      createdAt: -1, 
    },
  },
];
const result = await collection.aggregate(pipeline)

It appears that $search is not allowed in api version 1. So, I get this error: Database Error: MongoServerError: $search is not allowed with 'apiStrict: true' in API Version 1. Now if I set strict to false (which is the default), I do not get this error. but I am not sure if that is the right thing to do. The driver is not raising the exception anymore, but the $search command is still not part of the API Version 1. Right? I am a little confused based on what I quoted above. Do I need to do my search differently?

Hi @Akbar_Bakhshi3,

Welcome to the MongoDB Community

As per the error message the $search is not the part of API version 1, so let the apiStrict set as false. Let us know in case you are facing any other error while executing it.

Best regards,
Kushagra

1 Like