samedi 9 mai 2015

Express js Mongoose alternative to MySQL % Wildcard

I've been reading up and tried a few different code snippets that others have had success with, but I can't seem to get it to work.

What I'd like is for users to search using only part of the term i.e pe for 'peter'. I'd like to have a wildcard on the search term.

My code so far, which isn't working:

router.get('/:callsign', function(req,res){
var search = req.params.callsign;
var term = escape(search);
term = term.toUpperCase();
if(search=="*" || search==""){
    res.redirect("/");
}
User.find({'callsign' : new RegExp('^'+term+'$', "i") }, function(err, callsign){
    if(err)
    {
        console.log('No user found'+err);
        req.flash('message','Sorry, something went wrong. Try again.');
        res.render('callSearchResults'),{
            message: req.flash('message'), 
            title: 'Sorry, no results'
        }
    }
    if(callsign){
        console.log('Callsign:'+callsign+term);
        res.render('callSearchResults',{
            call: callsign,
            title: 'You searched for '+search,
            query: term
        });
    }else{
        console.log('No entries found'+search);
    }
});
});

Also, 'callsign' callback is constantly true - even when there are no results!

Aucun commentaire:

Enregistrer un commentaire