Meteor Collection.find在动态mongo查询中使用变量作为字段

时间:2014-12-04 14:47:15

标签: mongodb meteor

我正在尝试使用变量作为Collection.find查询中的字段说明符,但是tit只是忽略它

    var qry = "{\"" + field_name + "\":" + field_value + "}"
    console.log(qry)//  {"customer_active":true}
    Customers.find(qry).map(function(customer){// doesn't find anything
        console.log(customer)
        var groups = customer.customer_group_id.push(a._id)

        Customers.update({$set: {customer_group_id: groups}})
    })

如何构建动态查询

2 个答案:

答案 0 :(得分:8)

qry需要是一个对象,而不是一个字符串。所以建立它就像这样:

var qry = {};
qry[field_name] = field_value;

答案 1 :(得分:0)

我将查询包装在JSON.parse做了诀窍

    var qry = "{\"" + field_name + "\":" + field_value + "}"
    console.log(JSON.parse(qry))
    Customers.find(JSON.parse(qry)).map(function(customer){
        console.log(customer)
        var groups = customer.customer_group_id.push(a._id)

        Customers.update({$set: {customer_group_id: groups}})
    })