node.js - 将 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
})
当我使用.populate
mongoose 函数时,结果对象看起来有点像这样:
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"
}
解决方案
只需将架构中的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));
推荐阅读
- c# - C# VS2017 引用 .dll 和 .props
- python - Flask-Wtf 正则表达式和长度验证不起作用
- apache-spark - SparkFiles.get() 无法获取使用 spark-submit 的 --files 选项上传的文件
- javascript - 使用 AngularJs 在控制器中翻译文本
- android - 如何预先准备 RecyclerView 的 RecycledViewPool 以避免滚动时出现初始抖动?
- r - 将类似“Excel”的表格翻译成闪亮的/DT 代码?
- python - 使用较低分辨率的opencv捕获fps下降
- unit-testing - Mockito+Kotlin:如何模拟通过回调返回 T 的方法
- c# - 关闭 USB 串行端口会使端口不可用
- html - 在 a:before 伪元素上填充