express/nodejs:停止发送请求中的重复
问题描述:
如果对象已经存在,应该如何停止发布新对象的发布请求? 我粘贴了我的代码和json对象。我试过next();
,但它不起作用,无论如何都会创建一个带有其他ID的重复对象。我在使用PostTransaction函数前使用before
来检查产品是否已经存在。该请求包含的ID和express/nodejs:停止发送请求中的重复
index.js的店铺ID
const Transaction = require('./transactions/TransactionModel');
const TransactionCTL = require('./transactions/TransactionController');
Transaction.before('post', TransactionCTL.beforePostTransaction);
Transaction.register(router, '/transactions');
TransactionController.js
const beforePostTransaction = (req, res, next) => {
var id = req.body.id;
Transaction.findById(
id,
(err, data)=>{
if (!data){
next();
}
else{
var store = data.store;
store = JSON.stringify(store);
store = store.replace(/\"/g, "");
if(store !== req.body.store){ //update the whole object
next();
}
else{
//do what?
}
}
});
res.sendStatus(409);
}
JSON对象
[{
"_id": "596db06849822a13c97ba3f9",
"store": "596b088131ea400490897c50"
}]
答
不知道你是什么模型。但如果是猫鼬,你可以使用方法
.findOneAndUpdate(query,
update,
{upsert: true},
function (error, result) {
if (!error) { //if you need to do something else
}
});
哪里更新是你的对象。如果它不存在,将创建新项目,如果存在,则更新它。
这是我的模型:https://codeshare.io/5QmAdJ – Rachit
我不想更新它。我想用新对象完全覆盖它。 – Rachit
根据您的代码ID是唯一能够帮助您识别是否已插入的ID。因此,在这种情况下更新意味着覆盖存储参数,并保持ID(无论如何)。如果你不关心id的,只需要唯一的商店值,只需使用查询与商店,而不是id。 – MadDocNC