【问题标题】:Querying mongo db data from two schemas从两个模式中查询 mongo db 数据
【发布时间】:2021-05-22 16:45:24
【问题描述】:

我有一个 MEVN 应用程序。我为猫鼬中的订单和项目创建了两个模式。我想将它与项目 ID 结合起来。我该怎么做?

这是订单架构

var Order = new Schema({
stakeholder:mongoose.Types.ObjectId,
Items:[{
    item:mongoose.Types.ObjectId,
    quantity:Number,
    unitprice:Number
}],
total:Number,
final:Number
})

这是项目架构

var Item = new Schema({
name:String,
description:String,
unit:String,
type:Schema.Types.ObjectId
})

我想查询类似这种模式的项目。我不知道这是否可能,但我想像这种模式一样查询。

stakeholders,
items:[{itemid,name,description,quantity,unitprice}],
total,
final

你能举个例子解释一下吗?它会更有帮助。

【问题讨论】:

标签: json mongodb express vue.js mongoose


【解决方案1】:

也许你应该使用聚合运算符。

试试这个:

 const result = await Order.aggregate([
    {
      $lookup: {
        from: "Item", // collection to join
        localField: "Items.item", // field from the input documents
        foreignField: "_id", // field of the "from" collection
        as: "item_info", // output array field
      }
    }
 ]);

更多内容:https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

【讨论】:

    【解决方案2】:

    您可以通过两种方法实现这一点:

    1. 猫鼬种群
    2. MongoDB 聚合函数

    第一种方法

    更多详情:https://mongoosejs.com/docs/populate.html 如果我需要以下格式的数据,我会使用这种方法

    [
    {
      stakeholder,
      ...ordersColums,
      items: [
        {
          item: {...itemsColumns},
          quantity,
          unitprice
        }
    
      ]
    }
    ]
    
    

    为此可以做以下查询:

     Order.find().populate(['items.item'])
    

    如果您喜欢使用 formatOrder 函数,也可以对结果进行格式化。

     Order.find().populate(['items.item'])
      .then(result => formatOrder)
    

    第二种方法

    通过以下代码使用聚合功能:

    const result = await Order.aggregate([
        {
          $lookup: {
            from: "Item",
            localField: "Items.item",
            foreignField: "_id",
            as: "item_info",
          }
        },
        {
         $unwind or $populate // depending on the format you need
        }
    
     ]);
    

    如果您想将其格式化为特定格式,则可以使用 $unwind、$populate 聚合器函数并将它们添加到管道中。

    我个人更喜欢查找方法而不是聚合管道方法。

    【讨论】:

      【解决方案3】:

      您可以使用 populate 它就像 mongodb 中的 $lookup 一样,用于连接集合。 要使用填充,您需要 ref

      var Order = new Schema({
      stakeholder:mongoose.Types.ObjectId,
      Items:[{
          item: { type: mongoose.Types.ObjectId, ref: "Item " },
          quantity:Number,
          unitprice:Number
      }],
      total:Number,
      final:Number
      })
      

      使用填充连接两个基于之前插入项目字段的项目的_id的集合;

      await Order.find(filter).populate("Items.item")// path of field in schema
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-09
        • 2021-07-17
        • 1970-01-01
        • 1970-01-01
        • 2018-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多