重命名猫鼬响应中的键

阿萨德·哈亚特

我正在使用NodeJSmongoose

我有两个名为配置文件业务的集合具有以下架构。

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'}
    ]
});

相似地,

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

我查询个人资料时的示例响应

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

回报

{
  "_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
}

我希望business_ids字段在集合中保持不变,但在我的查询响应中将其重命名为business我怎样才能做到这一点。

穆罕默德尤斯里

您可以使用聚合管道 with$lookup而不是 find with populate

像这样的东西

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
    }
  }
])

你可以在这里测试Mongo Playground

希望能帮助到你

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章