Express Js+;猫鼬&x2B;加入

Express Js+;猫鼬&x2B;加入,express,mongoose,mongoose-populate,Express,Mongoose,Mongoose Populate,我有两个收藏。大小和项目。尺寸在项目中引用,我需要在查询项目时添加尺寸标题 大小集合 size:[{ _id: 123 title: S },{ _id: 456 title:M }] items:[{ title: item1, sizes:[{ _id: object I'd sizeid: 123 Price: 100 },{ _id: object I'd sizeid: 456, Price:

我有两个收藏。大小和项目。尺寸在项目中引用,我需要在查询项目时添加尺寸标题

大小集合

size:[{
_id: 123
title: S
},{
_id: 456
title:M
}]
items:[{
title: item1,
    sizes:[{
     _id: object I'd
     sizeid: 123
     Price: 100
     },{
       _id: object I'd
       sizeid: 456,
       Price: 150
      }]
   }]
项目集合

size:[{
_id: 123
title: S
},{
_id: 456
title:M
}]
items:[{
title: item1,
    sizes:[{
     _id: object I'd
     sizeid: 123
     Price: 100
     },{
       _id: object I'd
       sizeid: 456,
       Price: 150
      }]
   }]
如何执行连接以获得以下输出

items:[{
title: item1,
    sizes:[{
     _id: object I'd
     sizeid: 123
     size: S ----> from size collection
     Price: 100
     },{
       _id: object I'd
       sizeid: 456,
       size: M -----;> from size collection
       Price: 150
      }]
   }]

您需要将项目的属性大小模式设计为引用大小模式的ObjectId数组

const ItemSchema=新模式(
{
...
大小:[{type:Schema.Types.ObjectId,ref:'size'}]
}
);
然后,当你需要得到尺寸只是做

const result=wait Items.findOne(_id:itemId).populate('size');

我已添加为虚拟字段。我是MERN stack的初学者

itemSchema.virtual("sizemaster", {
  ref: "size",
  localField: "sizes.sizeId",
  foreignField: "_id",
});

itemSchema.virtual("itemsize").get(function (this: any) {
  const sizemaster = this.sizemaster;
  const itemsize = this.sizes.map(
    (s: {
      _id: any;
      sizeId: any;
      purchaseprice: any;
      mrp: any;
      salesprice: any;
      availablequantity: any;
    }) => {
      const sizeIndex = sizemaster.findIndex(
        (sm: { _id: { equals: (arg0: any) => any } }) => sm._id.equals(s.sizeId)
      );
      if (sizeIndex !== -1) {
        let itemsize = {
          itemsizeId: s._id,
          sizeId: s.sizeId,
          sizeTitle: sizemaster[sizeIndex].title,
          mrp: s.mrp,
          salesprice: s.salesprice,
          availablequantity: s.availablequantity,
        };

        return itemsize;
      }
    }
  );
  return itemsize;
});

.populate()
?是的,我使用了populate并在下面的答案中发布了解决方法。