美文网首页
mongoose 中使用 aggregate 聚合管道

mongoose 中使用 aggregate 聚合管道

作者: Wrestle_Mania | 来源:发表于2019-12-06 14:11 被阅读0次
  • model/order.js
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;
  • model/order_item.js
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;
  • app.js
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表其实不用引入的

相关文章

网友评论

      本文标题:mongoose 中使用 aggregate 聚合管道

      本文链接:https://www.haomeiwen.com/subject/yhnsgctx.html