mongoose 中使用 aggregate 聚合管道

2019-12-06  本文已影响0人  Wrestle_Mania
const mongoose = require("./db");

const OrderSchema = mongoose.Schema({
  order_id: String,
  uid: Number,
  trade_no: String,
  all_price: Number,
  all_num: Number
});

const OrderModel = mongoose.model("Order", OrderSchema, "order");

module.exports = OrderModel;
const mongoose = require("./db");

const OrderItemSchema = mongoose.Schema({
  order_id: String,
  title: String,
  price: Number,
  num: Number
});

const OrderItemModel = mongoose.model(
  "OrderItem",
  OrderItemSchema,
  "order_item"
);

module.exports = OrderItemModel;
const UserModel = require("./model/user");
const OrderModel = require("./model/order");
const OrderItemModel = require("./model/order_item");

OrderModel.aggregate(
  [
    {
      $lookup: {
        from: "order_item",
        localField: "order_id",
        foreignField: "order_id",
        as: "item"
      }
    }
  ],
  (err, docs) => {
    if (err) {
      console.log(err);
      return;
    }
    console.log(JSON.stringify(docs, null, 2));
  }
);

order_item表其实不用引入的

上一篇 下一篇

猜你喜欢

热点阅读