在javascript中追加对象

时间:2016-05-24 07:24:59

标签: javascript sails.js

在我的代码下面,我尝试在mainQuery对象中追加populate。如果我只传递类型,那么我得到预期的结果和查询也构建。如果我传递了两个类型和子类别,则查询被破坏,并且未按照预期的查询添加对象。请为此提供解决方案?

 System.out.println(new Object());

预期查询如下

mainQuery = Category.find();

if(req.param('types')) {
    searchKey = "types";
    typesObj.where = {
        id: 1
    };

    mainQuery.populate(searchKey, typesObj);
}   

if(req.param('subcat')) {
    searchkeySubCat = "subcategory";
    typesSubcat.where = {
        id: 1
    };

    mainQuery.populate(searchkeySubCat, typesSubcat);
}

mainQuery.exec(function (err, category) {

});

2 个答案:

答案 0 :(得分:2)

尝试如下:

function _getWhereClause(key, value) {
   return {where: {key: value}};
}

if (req.param('types')) {
    populateKey = 'types';
    mainQuery.populate(populateKey, _getWhereClause('id', 1));
}
// Do the same for any number of populate you want

最后执行查询:

mainQuery.exec(function (err, category) {

});

查看文档以获得更多理解 - http://sailsjs.org/documentation/reference/waterline-orm/queries/populate

答案 1 :(得分:0)

你在尝试什么基本上是用mainQuery对象进行方法链接。所以基本上你要形成一个查询,然后再使用该查询。我建议你把这个查询作为一个字符串。 例如。

mainQuery = "Category.find().";
mainQuery+= "populate("+searchKey+","+ typesObj+").";
mainQuery +="populate("+searchkeySubCat+","+ typesSubcat+").";
mainQuery +="exec(function (err, res) { console.log(res)});";

因此,当您访问mainQuery时,您将拥有:

   Category.find().populate('types', {where:     {id:1}}).populate('subcategory', {where: {id:1}}).exec(function (err, res) { 
console.log(res)
 });