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

查看:46
本文介绍了流星.js &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!

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

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