Express Js + 猫鼬 + 加入
Express Js + Mongoose + Joins
我有两个 collection。尺寸和物品。 size在items中引用,查询items时需要加上size title
尺码collection
size:[{
_id: 123
title: S
},{
_id: 456
title:M
}]
项目collection
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
}]
}]
您需要设计一个 属性 大小的 Items Schema 作为 ObjectID 数组,它将引用 Sizes Schema。
const ItemSchema = new Schema(
{
...
sizes: [{ type: Schema.Types.ObjectId, ref: 'Sizes' }]
}
);
然后当你需要调整尺码的时候
const result = await Items.findOne(_id: itemId).populate('sizes');
我已经添加为虚拟字段。我是 MERN 堆栈的初学者。
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;
});
我有两个 collection。尺寸和物品。 size在items中引用,查询items时需要加上size title
尺码collection
size:[{
_id: 123
title: S
},{
_id: 456
title:M
}]
项目collection
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
}]
}]
您需要设计一个 属性 大小的 Items Schema 作为 ObjectID 数组,它将引用 Sizes Schema。
const ItemSchema = new Schema(
{
...
sizes: [{ type: Schema.Types.ObjectId, ref: 'Sizes' }]
}
);
然后当你需要调整尺码的时候
const result = await Items.findOne(_id: itemId).populate('sizes');
我已经添加为虚拟字段。我是 MERN 堆栈的初学者。
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;
});