以链接的表为例,实现order,order_item表以order_id实现关联查询
1.联表查询
//order.js
const mongoose = require('./db');
const OrderSchema = new mongoose.Schema({
order_id:String,
status:String,
amount:Number
})
module.exports = mongoose.model("Order",OrderSchema,"order");
//order_item.js
const mongoose = require('./db');
const OrderItemSchema = new mongoose.Schema({
order_id:String,
title:String,
price:Number,
num:Number
})
module.exports = mongoose.model('OrderItem',OrderItemSchema,'order_item');
//app.js
const OrderModel = require('./model/order');
OrderModel.aggregate([{
$lookup:{
from:'order_item',
localField:"order_id",
foreignField:"order_id",
as:"items"
}
}],(err,docs)=>{
console.log(docs)
})
OrderModel.aggregate()是promise
const OrderModel = require('./model/order');
OrderModel.aggregate([{
$lookup:{
from:'order_item',
localField:"order_id",
foreignField:"order_id",
as:"items"
}
}]).then(data=>{
console.log(data)
})
2.order_item表查询title为酸奶的order表的order_id,以及all_price
var orderToItem = OrderItemModel.aggregate([{
$lookup:{
from:'order',
localField:'order_id',
foreignField:'order_id',
as:'infos'
}
},{
$match:{title:"酸奶"}
}])
3.mongoose获取ObjectId
{_id:mongoose.Types.ObjectId('xxxxx')}