【问题标题】:Meteor Collection.find use variable as field in dynamic mongo queryMeteor Collection.find 在动态 mongo 查询中使用变量作为字段
【发布时间】:2014-12-04 23:10:52
【问题描述】:

我试图在 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}})
    })

如何构建动态查询

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    qry 必须是对象,而不是字符串。所以改为这样构建它:

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

    【讨论】:

    • 我尝试时效果很好。也许你有错字?
    【解决方案2】:

    我将查询包装在 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}})
        })
    

    【讨论】:

    • 你想的太像 SQL 了,你必须拼凑一个字符串。试着理解@JohnnyHK 在说​​什么。您需要一个 JavaScript 对象而不是字符串。您不必构建字符串然后转换整个内容。您可以按照 JohnnyHK 向您展示的方式逐步构建 JavaScript 对象。
    猜你喜欢
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多