mongoose当中的聚合管道
聚合管道主要就可以实现表关联。
model>order.js
var mongoose = require("./db.js");
var OrderSchema = mongoose.Schema({
order_id: String,
uid: Number,
trade_no: String,
all_price: Number,
all_num: Number
});
module.exports = mongoose.model("Order", OrderSchema, "order");
model>order_item.js
var mongoose = require("./db.js");
var OrderItemSchema = mongoose.Schema({
order_id: String,
title: String,
price: Number,
num: Number
});
module.exports = mongoose.model("OrderItem", OrderItemSchema, "order_item");
app.js
var OrderModel = require("./model/order.js");
// 查询order表的数据
OrderModel.find({}, function(err, docs) {
console.log(docs);
});
app.js order表关联order_item表
var OrderModel = require("./model/order.js");
// // 查询order表的数据
// OrderModel.find({}, function(err, docs) {
// console.log(docs);
// });
OrderModel.aggregate(
[
{
$lookup: {
from: "order_item",
localField: "order_id",
foreignField: "order_id",
as: "items"
}
}
],
function(err, docs) {
if (err) {
console.log(err);
return;
}
console.log(JSON.stringify(docs));
}
);
[
{
"_id": "5e85a2d513e466f7ac6a236f",
"order_id": "1",
"uid": 10,
"trade_no": "111",
"all_price": 100,
"all_num": 2,
"items": [
{
"_id": "5e85a2d613e466f7ac6a2372",
"order_id": "1",
"title": "商品鼠标1",
"price": 50,
"num": 1
},
{
"_id": "5e85a2d613e466f7ac6a2373",
"order_id": "1",
"title": "商品键盘2",
"price": 50,
"num": 1
},
{
"_id": "5e85a2d613e466f7ac6a2374",
"order_id": "1",
"title": "商品键盘3",
"price": 0,
"num": 1
}
]
},
{
"_id": "5e85a2d613e466f7ac6a2370",
"order_id": "2",
"uid": 7,
"trade_no": "222",
"all_price": 90,
"all_num": 2,
"items": [
{
"_id": "5e85a2d613e466f7ac6a2375",
"order_id": "2",
"title": "牛奶",
"price": 50,
"num": 1
},
{
"_id": "5e85a2d613e466f7ac6a2376",
"order_id": "2",
"title": "酸奶",
"price": 40,
"num": 1
}
]
},
{
"_id": "5e85a2d613e466f7ac6a2371",
"order_id": "3",
"uid": 9,
"trade_no": "333",
"all_price": 20,
"all_num": 6,
"items": [
{
"_id": "5e85a2d613e466f7ac6a2377",
"order_id": "3",
"title": "矿泉水",
"price": 2,
"num": 5
},
{
"_id": "5e85a2d713e466f7ac6a2378",
"order_id": "3",
"title": "毛巾",
"price": 10,
"num": 1
}
]
}
]
app.js order表关联order_item表 all_price字段 大于90
var OrderModel = require("./model/order.js");
// // 查询order表的数据
// OrderModel.find({}, function(err, docs) {
// console.log(docs);
// });
OrderModel.aggregate(
[
{
$lookup: {
from: "order_item",
localField: "order_id",
foreignField: "order_id",
as: "items"
}
},
{
$match: { all_price: { $gte: 90 } }
}
],
function(err, docs) {
if (err) {
console.log(err);
return;
}
console.log(JSON.stringify(docs));
}
);
根目录:order.js 查询id为 5e85a2d613e466f7ac6a2373 的数据
// 查询order_item,找出商品名称是酸奶的商品,酸奶这个该商品对应的订单的订单号,以及订单的总价格。
var OrderItemModel = require("./model/order_item.js");
var OrderModel = require("./model/order.js");
OrderItemModel.find({ _id: "5e85a2d613e466f7ac6a2373" }, function(err, docs) {
console.log(docs);
});
来源:oschina
链接:https://my.oschina.net/u/4446873/blog/4267566