7

In mongoose, I am using populate on field. After populate need to change field name. Is it possible?

I am populate on company_id. It is showing me company_id: Object but I need to change its name as company:Object.

    this.model(companySessionModelName)
    .find(
          {
            "company_session.end_date":{$lt:arg_date},
            "company_session.status":"active"
          },
          {
            "company_id":1,
            "company_session.$":1
          }
        )
.populate("company_id","name")                                            
.exec(function(err, _s_user) {
         if(err){
           cb(err);
         }else{
            cb(null,_s_user);
         }   });

Output:

[
            {
                "_id": "5a829132a83f321e380cd17f",
                "company_id": {
                    "_id": "5a7ad080f8c88a231113676f",
                    "name": "Stephania Rath"
                },
                "company_session": [
                    {
                        "start_date": "2018-02-14T00:00:00.000Z",
                        "end_date": "2018-02-16T00:00:00.000Z",
                        "_id": "5a829132a83f321e380cd180",
                        "status": "active"
                    }
                ]
            }
        ]

Excepted Output:

[
            {
                "_id": "5a829132a83f321e380cd17f",
                "company": {
                    "_id": "5a7ad080f8c88a231113676f",
                    "name": "Stephania Rath"
                },
                "company_session": [
                    {
                        "start_date": "2018-02-14T00:00:00.000Z",
                        "end_date": "2018-02-16T00:00:00.000Z",
                        "_id": "5a829132a83f321e380cd180",
                        "status": "active"
                    }
                ]
            }
        ]
Nits
  • 520
  • 6
  • 21
  • As far as i know it's not possible unless you have a virtual populate. If you were performing on a field you can use $rename(check mongodb documentation) whereas for populate field you should have created a virtual populate. – Kannan T Feb 13 '18 at 12:56
  • Does this answer your question? [How to rename path in response for populate](https://stackoverflow.com/questions/38484504/how-to-rename-path-in-response-for-populate) – Avius Jan 26 '21 at 20:54

0 Answers0