简体   繁体   English

express / nodejs:停止发布请求中的重复项

[英]express/nodejs: stop duplicates in post request

What should I do to stop the post request from posting new object if the object already exists? 如果对象已经存在,我应该怎么做才能阻止发布请求发布新对象? I have pasted my code and json object. 我已经粘贴了代码和json对象。 I have tried next(); 我已经尝试过next(); but it doesnt work and a duplicate object with some other id is created no matter what. 但它不起作用,并且无论如何都会创建具有其他ID的重复对象。 I am using before beforePostTransaction function to check if the product already exists. 我在使用beforePostTransaction函数before来检查产品是否已经存在。 The request contains the id and the store id of the 该请求包含ID的ID和商店ID

index.js index.js

const Transaction = require('./transactions/TransactionModel');
const TransactionCTL = require('./transactions/TransactionController');
Transaction.before('post', TransactionCTL.beforePostTransaction);
Transaction.register(router, '/transactions');

TransactionController.js 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 object json对象

[{
    "_id": "596db06849822a13c97ba3f9",
    "store": "596b088131ea400490897c50"
}]

Not sure what is your model. 不确定您的模型是什么。 But if it is mongoose you can use method 但是如果是猫鼬,你可以使用方法

.findOneAndUpdate(query,
        update,
        {upsert: true},
        function (error, result) {
          if (!error) { //if you need to do something else
          }
        });

Where update is your object. 更新是您的对象。 It will create new item if it not exist and update it if it exist. 如果不存在,它将创建新项目,如果存在,将对其进行更新。

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

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