meteor.js & mongoDB - query with multiple fields

删除回忆录丶 提交于 2019-12-12 18:02:19

问题


CONTEXT

I am trying to create a search functionality allowing users to fill in multiple fields, submit, and see a list of matching items from one collection. I do this using a form on the front end, which updates session variables on back-end, which are then passed as query to a mongodb collection.

HOW IT SHOULD WORK

If a user submits a venue size, then venues of that size are shown. If only a location is typed in, then venues within that location are shown. If both a size and a location are submitted, then venues that match both criteria are shown.

HOW IT ACTUALLY WORKS

If nothing is filled in, pressing search yields all items in the collection. Submitting both location and size yields venues that match both criteria. However, filling in only one field and leaving the other empty yields nothing in results. I'm wondering why this might be - it's almost as if the query is searching for a field that literally contains ''... but then why don't I see this behavior when leaving both fields empty? Help much appreciated!

CODE SNIPPET

//Search Form Helper
Template.managevenues.helpers({
  venue: function () {

    var venueNameVar = Session.get('venueNameVar');
    var venueLocationVar = Session.get('venueLocationVar');

    if(venueNameVar || venueLocationVar){
        console.log(venueNameVar);
        console.log(venueLocationVar);

        return Venues.find({
            venueName: venueNameVar,
            'venueAddress.neighbourhood': venueLocationVar
    });
    } else {
        return Venues.find({});
    }
});

回答1:


The answer lies in your query

Venues.find({
        venueName: venueNameVar,
        'venueAddress.neighbourhood': venueLocationVar
});

If you don't have one of your vars set it will look like this...

{
   venueName: undefined,
   'venueAddress.neighbourhood':'someVal'
}

So it would match any venue that doesn't have a name and is in some neighborhood.

A better approach would be to only set query criteria if there's a value to search...

var query = {};
if(Session.get('venueNameVar')) {
   query.venueName = Session.get('venueNameVar');
}
if(Session.get('venueLocationVar') {
   query.venueAddress = {
       neighbourhood : Session.get('venueLocationVar');
   }
}
return Venues.find(query);

I think this will work a bit better for you!



来源:https://stackoverflow.com/questions/34232241/meteor-js-mongodb-query-with-multiple-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!