Frage

When the following code in my node.js-application is executed I get an Error saying:

SyntaxError: Invalid regular expression: /ha/: Nothing to repeat at new RegExp () at Object.store.findSimilarSongs

app.js snippet:

app.get('/search', function (req, res, next) {

    store.findSimilarSongs(req.query.search, function (err, songs) {
        if (err) {
            res.writeHead(500, "An Error occurred");
            next(err);
        }
        else {
            res.writeHead(200, {
                'Content-Type': 'application/json'
            });
            res.write(JSON.stringify(songs));
            searchQuery=[];
        }
        res.end();
    });
});

the function "findSimilarSongs" in my store.js:

findSimilarSongs: function (query, callback) {
        db.music.find({$or:[{'title': new RegExp("*"+query+"*", "i")},{'interpret': new RegExp("*"+query+"*", "i")}]}, callback);
    }

I am pretty new to regular expressions especially combined with mongodb/mongoskin. Until the error occurs, everything works pretty much fine. The ha mentioned in the error-message is exactly what I typed into the searchbar.

Sadly I do not have the option to do this task with any other means, but javascript/jquery, node.js(modules:express, mongoskin) and mongodb.

War es hilfreich?

Lösung

It says "nothing to repeat", as the regex you constructed was /*hal*/. That's definitely invalid - you cannot start with the repetition operator. I guess you either wanted a fuzzy match:

new RegExp(".*"+query+".*, 'i')

or a literal star:

new RegExp("\\*"+query+"\\*", 'i')
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top