【问题标题】:Joining collections in mongodb with node js使用节点 js 在 mongodb 中加入集合
【发布时间】:2020-04-13 17:47:57
【问题描述】:

我在 mongodb“组件”和“机身”中有两个集合,我正在尝试将它们连接在一起(具有一对多关系)。我有以下代码从数据库中分别获取机身和组件数据,但是经过几天的努力,我无法弄清楚如何将两者连接在一起。我假设我需要使用 $lookup 来实现所需的结果,但在构建代码方面的任何帮助将不胜感激。

我的模型如下,我正在尝试加入关联机身下的所有组件记录。 Component 上的 airframe 字段保存了相关的 Airframe 的 id。

const airframeSchema = mongoose.Schema({
  name: { type: String, required: true },
  sNumber: { type: String, required: true },
  aStatus: { type: String, required: true },
  components: [ { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Component' } ]
});
module.exports = mongoose.model('Airframe', airframeSchema);

const componentSchema = mongoose.Schema({
  name: { type: String, required: true },
  serial: { type: String, required: true }, 
  type: { type: String, required: true },
  airFrame: { 
    type: mongoose.Schema.Types.ObjectId, 
    required: true,
    ref: 'Airframe'},
});

module.exports = mongoose.model('Component', componentSchema);

AirFramesService 如下。我想将组件数据加入一个名为“组件”的数组下。

  getAirframes() {
    this.http
      .get<{ message: string; airframes: any }>("http://3.135.49.46:8080/api/airframes")
      .pipe(
        map(airframeData => {
          return airframeData.airframes.map(airframe => {
            return {
              name: airframe.name,
              sNumber: airframe.sNumber,
              aStatus: airframe.aStatus,
              id: airframe._id,
            };
          });
        })
      )
      .subscribe(transformedAirframes => {
        this.airframes = transformedAirframes;
        this.airframesUpdated.next([...this.airframes]);
      });
  }

  getAirframeUpdateListener() {
    return this.airframesUpdated.asObservable();
  }

  getAirframe(id: string) {
    return this.http.get<{ _id: string; name: string; sNumber: string ; aStatus: string}>(
      "http://3.135.49.46:8080/api/airframes/" + id
    );
  }

机身航线代码如下:

router.get("", (req, res, next) => {
  Airframe.find().then(documents => {
    res.status(200).json({
      message: "Airframes fetched successfully!",
      airframes: documents
    });
  });
});

这里是ts组件文件中获取机身数据的代码如下。

  constructor( public airframesService: AirframesService) {
    this.airframesService.getAirframes();
    this.airframesSub = this.airframesService.getAirframeUpdateListener()
      .subscribe((airframes: Airframe[]) => {
        this.isLoading = false;
        this.airframes = airframes;
        }, 0);
    });
  }

期望的结果如下(目前我只得到机身数据):

{
    _id: "123"
    name: "Airframe01"
    sNumber: "757"
    aStatus: "Active"
    id: "5e8052ad1fa18f1c73524664"
    components: [
      {
       name: "Left Tank",
       serial: "3456789", 
       type: "Landing Gear",
       airFrame: "5e8052ad1fa18f1c73524664"
       },
       {
       name: "Right Tank",
       serial: "45678", 
       type: "Landing Gear",
       airFrame: "5e8052ad1fa18f1c73524664"
       }
    ]
}

【问题讨论】:

  • 你试过用moongose填充方法mongoosejs.com/docs/populate.html
  • 我做到了,但无法弄清楚。代码会去哪里?在 AirFramesService 还是 ts 组件文件中?

标签: node.js angular mongodb express


【解决方案1】:

您的文档结构已经在两个模型之间建立了一对多的关系,您可以使用 Mongoose 人口来获得您在问题中描述的加入。填充代码应该在机身路径中的某个位置,如下所示:

router.get("", (req, res, next) => {
  // Notice the populate() method chain below
  Airframe.find().populate('components').then(documents => {
    // The documents output should have their "components" property populated
    // with an array of components instead of just Object IDs.
    res.status(200).json({
      message: "Airframes fetched successfully!",
      airframes: documents
    });
  });
});

您可以阅读更多关于猫鼬种群的信息here

【讨论】:

  • 谢谢 Tunmee,这为我指明了正确的方向。我最终使用了虚拟填充,所以我没有在机身记录上得到一个不断增长的数组,因为列表可能会变得很长。这允许我加入记录,只将机身 ID 保存在评论记录中。再次感谢您的帮助!
猜你喜欢
  • 2015-10-07
  • 2019-08-02
  • 2018-08-16
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 2019-10-21
  • 2019-08-03
  • 2018-08-21
相关资源
最近更新 更多