node.jsregexmongodbpathstartswith

How to write a database query in Node.js/MongoDb using regex that returns a result when a field starts with a given string?


So far I have this code, that attempts to remove a "document" (a path string, like "./documents/images") from a database, as well as all subdocuments (path strings that start with the same substring, like "./documents/images/flower.jpeg"):

async function removeUserDocument(document) {

    const regex = new RegExp(`/^${document}/`);

    await db.collection.deleteMany(

        {
            "document": {

                $regex: regex
            }
        }
    );
}

However, it isn't quite working as it doesn't return any results. I tried it with a few different syntaxes I found, but none of them seemed to work. What would be the correct way to formulate this regex?


Solution

  • The way you built your regex is wrong because it includes slashes which would be only part of a regex literal (which you can't use because of your dynamic content), so it should just be:

    const regex = new RegExp(`^${document}`); 
    
    

    Also, the code can be simplified, because if you use $regex, you can provide a string which is interpreted as regex, not an actual RegExp (so you wouldn't need to use new RegExp first):

    await db.collection.deleteMany({
      document: { $regex: `^${document}` }
    })
    

    Or, since you already have an actual RegExp, you could also just pass it directly:

    await db.collection.deleteMany({
      document: regex
    })
    

    By the way, this code will break if your document variable has special characters because you don't escape them. I'd suggest using a package such as regexp.escape or, if you are on node.js 24+, the built-in function RegExp.escape.