简体   繁体   English

将 collections 加入 mongodb 与节点 js

[英]Joining collections in mongodb with node js

I have two collections in mongodb "components" and "airframes" which I am trying to join together (with a one to many relationship).我在 mongodb “组件”和“机身”中有两个 collections 我试图将它们连接在一起(一对多的关系)。 I have the following code which gets the airframe and component data separately from the database, however after days of effort, I cannot figure out how to join the two together.我有以下代码从数据库中分别获取机身和组件数据,但是经过几天的努力,我无法弄清楚如何将两者连接在一起。 I assume I need to use $lookup to achieve the desired result but any assistance in constructing the code would be greatly appreciated.我假设我需要使用 $lookup 来获得所需的结果,但在构建代码方面的任何帮助将不胜感激。

my models are as follows and I am trying to join all the component records under the associated Airframe.我的模型如下,我正在尝试加入相关机身下的所有组件记录。 the airframe field on the Component holds the related Airframes' id.组件上的机身字段包含相关机身的 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);

the AirFramesService is as follow. AirFramesService 如下。 I would like to join the component data under a array called "component".我想将组件数据加入一个名为“组件”的数组下。

  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
    );
  }

The airframes route code is as follows:机身航线代码如下:

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

and here is the code within the ts component file that gets the airframe data is as follows.这是获取机身数据的ts组件文件中的代码如下。

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

the desired outcome would be the following (at the moment I only get the airframe data):期望的结果如下(目前我只得到机身数据):

{
    _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"
       }
    ]
}

Your document structure already established a one-to-many kinda relationship between the two models, you can use Mongoose population to get the join you described in the question.您的文档结构已经在两个模型之间建立了一对多的关系,您可以使用 Mongoose 人口来获得您在问题中描述的连接。 The populate code should be somewhere in the airframes route like this:填充代码应该在机身路径中的某个位置,如下所示:

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
    });
  });
});

You can read more about Mongoose population here .您可以在此处阅读有关 Mongoose 种群的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM