多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ### mongoose 关联查询 * [ ] 一对多 比如订单表,一个订单对应多个商品,订单和商品属于一对多 ~~~ async getOrder() { return await this.ctx.model.Order.aggregate([ { $lookup: { from: 'order_item', localField: 'order_id', foreignField: 'order_id', as: 'items' } } ]) } ~~~ >[info] $lookup 主表关联 > from 关联子表 > localField 主表id ( 与子表关联的字段 ) > foreignField 关联外键 (子表和主表关联的字段) > as 关联字段 ~~~ [ { "_id": "5d209e01e9d8ac37a0976bfd", "order_id": "1", "uid": "10", "trade": "111", "all_price": "100", "all_num": "2", "status": "0", "items": [ { "_id": "5d209e33e9d8ac37a0976bfe", "order_id": "1", "title": "鼠标", "price": "60", "num": "1" }, { "_id": "5d209e4fe9d8ac37a0976bff", "order_id": "1", "title": "键盘", "price": "90", "num": "16" }, { "_id": "5d209e63e9d8ac37a0976c00", "order_id": "1", "title": "液晶屏幕", "price": "160", "num": "90" } ] } ] ~~~