Search code examples
node.jsmongodbmongoosemongoose-schema

rename key in mongoose response


I am using NodeJS and mongoose.

I have two collections named profiles and businesses with following schema.

ProfileSchema = new Schema ({
    first_name: {type: String, required: true},
    last_name: {type: String, required: true},
    age: {type: Number, required: true},
    business_ids: [
         {type: schema.Types.ObjectId, ref: 'business'}
    ]
});

Similarly,

BusinessSchema = new Schema ({
        title: {type: String, required: true},
        type: {type: String, required: true},
        address: {type: String, required: true},        
    });

A sample response when i query profile is

profiles.find().populate("business_ids")   

returns

{
  "_id": "5bf5fbef16a06667027eecc2",
  "first_name": "Asad",
  "last_name": "Hayat",
  "age": "26",
  "business_ids": [
    {
      "_id": "5ae14d2e124da839884ff939",
      "title": "Business 1",
      "type": "B Type",
      "address": "Business 1 Address"
    },
    {
      "_id": "5ae14d2e124da839884ff93b",
      "title": "Business 2",
      "type": "C Type",
      "address": "Business 2 Address"
    }
  ],
  "__v": 0
}

I want the business_ids field to remain same in collection, but rename it to businesses in my query responses. How can i achieve this.


Solution

  • you can use the aggregate pipeline with $lookup instead of find with populate

    something like this

    db.profile.aggregate([
      {
        $lookup: {
          from: "business",
          localField: "business_ids",
          foreignField: "_id",
          as: "businesses"
        }
      },
      {
        $project: {
          business_ids: 0 // this is to remove the business_ids array of ObjectIds, if you want to keep it, you can omit this $project step
        }
      }
    ])
    

    you can test it here Mongo Playground

    hope it helps