juanObrach
juanObrach

Reputation: 158

Populate in Mongodb

I'm so confused about how Mongodb work. Those are my controllers to my methods. When I submit a form in my page, the "populate()" works only when I recharge my site." But I need do this when I submit. Suppose I need add the "populate()" options in my Add Cases controller.

Do not know how to make it work

/**
    * Get Cases
    *
    * @method get
    * @param req {Object} Request from http
    * @param res {Object} response to http
    */
    function get(req,res){

        var response = {
            code:400,
            result:{}
        };

        var skip = (req.body.skip)?req.body.skip:0;
        var limit = (req.body.limit)?req.body.limit:20;
        var query = {};

        var caseCb = function(err,caseDoc){
            if(err){
                res.json(response);
                return;
            }
            response.code = 200;
            response.result = caseDoc;
            res.json(response);
        };

        params.Pandem.case_model.find(query).populate('disease').exec(caseCb)
    }


/**
     * Add Case
     *
     * @method add
     * @param req {Object} Request from http
     * @param res {Object} response to http
     */
    function add(req,res){

        var response = {
            code:400,
            result:{}
        };

        var caseObj = {
            name: req.body.name,
            location: [req.body.location.longitude,req.body.location.latitude],
            disease:req.body.disease._id
        };


        var caseCb = function(err,caseDoc){
            if(err){
                response.result = err;
                res.json(response);
                return;
            }
            response.code = 200;
            response.result = caseDoc;
            res.json(response);
        };
        params.Pandem.case_model.create(caseObj,caseCb);
    }

Upvotes: 0

Views: 1061

Answers (1)

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

Populate works only on find(), but what you're doing in your 'add' function is creating a Pandem document. If you want to return the Pandem document, with decease populated after you create it, you can call populate after the document is created.

var caseCb = function(err,caseDoc){
    if(err){
        response.result = err;
        res.json(response);
        return;
    }

    caseDoc.populate('disease', function (err, caseDocPopulated){
      response.code = 200;
      response.result = caseDocPopulated;
      res.json(response);
    })
};
params.Pandem.case_model.create(caseObj,caseCb);

Upvotes: 1

Related Questions