在javascript中追加对象

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

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) {

});

预期查询如下

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

最佳答案 请尝试以下方式:

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

点赞