首页 > 解决方案 > 将 mongo 中的 ref 字段(使用 mongoose)填充到不同的路径

问题描述

我有一个看起来像这样的模型对象:

   OrderSchema = new Schema({
        order_id: {type: String, unique: true},
        customer: {
            address:addressModel,
            first_name : {type:String, default:''},
            last_name : {type:String, default:''},
            company : {type:String, default:''},
            phone1 : phoneModel,
            phone2 : phoneModel,
            email : {type:String},
            mask : {type:Boolean, default:false},
        },
        retailer: {
            _id: { type: Schema.Types.ObjectId, ref: 'Retailer' }
        }
    }

和零售商看起来像这样:

RetailerSchema = new Schema({
    company: {type:String, required: true},
    identifier: {type:String, required: true, unique: true},
    first_name: {type:String},
    last_name: {type:String},
    address: addressModel,
    phone1:phoneModel,
    phone2:phoneModel
})

当我使用.populatemongoose 函数时,结果对象看起来有点像这样:

queryCall.populate('retailer._id','company address')

...

 "retailer": {
        "_id": {
            "address": {
                "address1": "51 Astor Place",
                "address2": "",
                "city": "New York",
                "state": "NY",
                "zip": "10003"
            },
            "_id": "5d4482a35555d200208b3cd4",
            "company": "123"
        }
    }

有没有办法创建一个地图,在我填充结果对象之后,它只是填充的字段的扩展,因此,如下所示。我正在尝试查看是否有办法将结果填充到结果对象上的不同路径。

   "retailer": {
        "_id": "5d4482a35555d200208b3cd4",
        "address": {
                "address1": "51 Astor Place",
                "address2": "",
                "city": "New York",
                "state": "NY",
                "zip": "10003"
            }
        },
        "company": "123"
    }

标签: node.jsmongodbmongoosepopulate

解决方案


只需将架构中的retailer字段更改为:OrderSchema

retailer: { type: Schema.Types.ObjectId, ref: 'Retailer' }

.populate像这样调用:

queryCall.populate('retailer', 'company address')

如果您无法编辑架构,那么您可以使用如下聚合:

OrderSchema.aggregate([/* { $match: { // put your conditions here }  } */])
  .lookup({ from: 'retailers', localField: 'retailer._id', foreignField: '_id', as: 'retailer' })
  .unwind('retailer')
  .project({
    // other fields,
    retailer: {
      address: 1,
      company: 1
    }
  })

或者,如果您只想使用 javascript:

return orders.map(order => (order.retailer = order.retailer._id, order));

推荐阅读