流星mongoDB-具有多个字段的查询 [英] meteor.js & mongoDB - query with multiple fields

查看:97
本文介绍了流星mongoDB-具有多个字段的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文

我正在尝试创建一种搜索功能,允许用户填写多个字段,提交并查看一个集合中匹配项的列表.我使用前端的表单进行此操作,该表单在后端更新会话变量,然后将其作为查询传递给mongodb集合.

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.

应该如何工作

如果用户提交场地大小,则会显示该大小的场地.如果仅键入一个位置,那么将显示该位置内的场所.如果同时提交了大小和位置,则会显示同时符合两个条件的场所.

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.

实际工作原理

如果未填写任何内容,则按搜索将产生集合中的所有项目.同时提交位置和大小会产生符合两个条件的场所.但是,仅填写一个字段,而将其他字段留空则不会产生任何结果.我想知道为什么会这样-好像查询正在搜索字面意义上包含''...的字段一样,但是为什么当两个字段都为空时却看不到这种行为?帮助非常感谢!

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!

代码片段

//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({});
    }
});

推荐答案

答案就在您的查询中

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

如果您没有设置vars之一,它将看起来像这样...

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!

这篇关于流星mongoDB-具有多个字段的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆