以链接的表为例,实现order,order_item表以order_id实现关联查询

1.联表查询

  1. //order.js
  2. const mongoose = require('./db');
  3. const OrderSchema = new mongoose.Schema({
  4. order_id:String,
  5. status:String,
  6. amount:Number
  7. })
  8. module.exports = mongoose.model("Order",OrderSchema,"order");
  1. //order_item.js
  2. const mongoose = require('./db');
  3. const OrderItemSchema = new mongoose.Schema({
  4. order_id:String,
  5. title:String,
  6. price:Number,
  7. num:Number
  8. })
  9. module.exports = mongoose.model('OrderItem',OrderItemSchema,'order_item');
  1. //app.js
  2. const OrderModel = require('./model/order');
  3. OrderModel.aggregate([{
  4. $lookup:{
  5. from:'order_item',
  6. localField:"order_id",
  7. foreignField:"order_id",
  8. as:"items"
  9. }
  10. }],(err,docs)=>{
  11. console.log(docs)
  12. })

OrderModel.aggregate()是promise

  1. const OrderModel = require('./model/order');
  2. OrderModel.aggregate([{
  3. $lookup:{
  4. from:'order_item',
  5. localField:"order_id",
  6. foreignField:"order_id",
  7. as:"items"
  8. }
  9. }]).then(data=>{
  10. console.log(data)
  11. })

2.order_item表查询title为酸奶的order表的order_id,以及all_price

  1. var orderToItem = OrderItemModel.aggregate([{
  2. $lookup:{
  3. from:'order',
  4. localField:'order_id',
  5. foreignField:'order_id',
  6. as:'infos'
  7. }
  8. },{
  9. $match:{title:"酸奶"}
  10. }])

3.mongoose获取ObjectId

  1. {_id:mongoose.Types.ObjectId('xxxxx')}