'Node/Mongoose Error - Can't use $expr with String

My goal is to create a query that searches for a partial string in a particular field - from the last index of a nested array in a MongoDB database. My constraint is that I must use a .find() query.

I'm using Mongoose 6.2.9 and MongoDB 5.0.4 - I've developed a query that works perfectly in MongoDB Compass, but Mongoose seems to be having issues with:

(node:48632) UnhandledPromiseRejectionWarning: Error: Can't use $expr with String.

The call I'm trying to make:

findQuery['statuses.schema'] = {
    $expr: {
        $regexMatch: {
            input: {
                $arrayElemAt: ['$statuses.schema', -1]
            },
            regex: "sample|regex|here",
            options: 'i'
        }
    }
};

The issue seems to be placing $statuses.schema inside quotation marks (cast as a string) - but without these quotation marks, I seem to get an error in my GraphQL response (this query is part of a resolver for a GraphQL API) that would lead me further away from a solution:

    {
      "message": "$statuses is not defined",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],

Edit: Added Schema

const statusSchema = mongoose.Schema({
    timestamp: { type: String },
    status: { type: String },
    test: { type: String },
    symptom: [symptomSchema],
    code: { type: String },
});

const serverSchema = mongoose.Schema({
    ipAddress: { type: String },
    index: { type: String },
    serialNumber: { type: String },
    model: { type: String },
    configCode: { type: String },
    operator: { type: String },
    onlineStatus: {type: Boolean, default: false},
    repairCount: { type: String },
    lastRepair: { type: String },
    customer: { type: String },
    location: [locationSchema],
    inRepair: { type: String },
    rack: { type: String },
    statuses: [statusSchema],
    schema_version: { type: String },
}, { _id: true});

So in short, MongoDB seems to require "$myArray.myField" be a string, but Mongoose cannot handle it being a string when nested under $expr. What am I doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source