Das*_*sto 6 postgresql node.js sequelize.js
我正在使用Node/Sequelize处理Postgres数据库.该数据库有3个相关模型,Store,Product和Offer.商店可以有很多产品,但产品属于一个商店.产品可以有多个优惠,而优惠属于一个产品.为了使其更复杂,Product和Offer都有各种类型的代理ID,使人们可以更容易地将它们与真实世界的产品相关联,而不是注意自动生成的ID.因此,所有产品都需要通过'sku'查找,并且'offer_id'和商品的所有商品都会通过他们的sku而不是ID添加到产品中.
const Product = sequelize.define(
"product",
{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
sku: {
type: Sequelize.STRING,
allowNull: false,
}
},
{
indexes: [{ fields: ["sku", "storeId"], unique: true }]
}
);
const Offer = sequelize.define(
"offer",
{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
offer_id: {
type: Sequelize.STRING,
allowNull: false,
},
product_sku: {
type: Sequelize.STRING,
allowNull: false,
}
}
,
{
indexes: [{ fields: ["offer_id", "productId"], unique: true }]
}
);
Run Code Online (Sandbox Code Playgroud)
给定一系列要约,我需要更新要约(如果存在)或创建它(如果它尚不存在).
function addOffer(newOffer, storeId) {
//Find a product to add the offer to
return Product.findOne({
where: { sku: newOffer.product_sku, storeId: storeId }
}).then(function(product) {
if (product) {
// Product found, check if offer exists
return Offer
.findOne({ where: { offer_id: newOffer.offer_id, productId: product.id } })
.then(function(offer) {
if (offer) {
// update offer
return offer.update({...newOffer });
} else {
// insert new offer
return Offer.create({...newOffer,productId: product.id });
}
})
.catch(err => console.log(err));
} else {
// Product not found
return false;
}
});
}
exports.add_offers = async function(req, res) {
const storeId = req.body.storeId;
const offers = [
{
"offer_id": "122",
"product_sku": "5722719"
},
{
"offer_id": "123",
"product_sku": "5722719"
},
{
"offer_id": "124",
"product_sku": "5822625"
}
];
for (const offer of accepted) {
addOffer(offer, storeId)
.then(function(result) {
//res.status(200).send({ success: true });
})
.catch(err => {
//handle error
});
}
}
Run Code Online (Sandbox Code Playgroud)
我试图解决的主要问题是我的addProduct()函数.因为我必须首先通过sku + storeId查找项目以查找productID.然后使用offer_id + productId检查商品是否已存在.当我最终呼叫更新或创建优惠时,我每次提供3个网络电话.如果我的商品阵列具有任何显着的大小,那么它将是非常低效的.
有更简单的方法吗?