Add object to javascript

Below my code, I am trying to add padding to a mainQuery object. If I pass only types, I get the expected result and request. If I pass both types and a subcategory, then the request was broken and the object was not added as the expected request below. Please give a solution for this?

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

});

Expected request below

Category.find().populate('types', {where: {id:1}}).populate('subcategory', {where: {id:1}}).exec(function (err, res) { 
    console.log(res)
})
+4
source share
2 answers

Try the following:

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

Finally, run the query:

mainQuery.exec(function (err, category) {

});

Check out the documentation for a deeper understanding - http://sailsjs.org/documentation/reference/waterline-orm/queries/populate

+2
source

, 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)
 });
0

All Articles