简体   繁体   中英

Why the data is being stored twice using mongoose?

I want to save a number of data in a property call cases. What I did was to iterate a list of data that I want to store, and then adding each data to the document's property. But the problem is that each data is being stored twice. I found a person in github who had the same issue, he said the problem was with nodemon, but I ran the sever again without nodemon and is the same problem.

Also found a question in stack saying that when a callback is applied it results in saving it twice, also the case is diferent from mine:

Why does using mongoose callback result in saving data twice?

I tried removing the callback, but I still have the same problem. (I dont think that a callback might do that)

This is the code:

var UserSchema = Schema({
    user: {type: String},
    password: {type: String},
    name: {type: String},
    privilege: {type: String},
    cases: {type: Array}
})

var user = db.model('User', UserSchema , "users");

app.post("/addCases", function(req, res){

    user.find({user: req.body.user}, async function(err, doc) {

        if(err) {
            console.log(err);
        } else {

            for (const iterator of req.body.list) {

                await user.updateOne({user: req.body.user},
                    { $push: {cases: iterator}}, {useFindAndModify: false}, function(err, raw) {
                        if(err) {
                            console.log(err);
                        } else {
                            console.log(value + ' <----- Value');
                    }
                });
            }
        }
    });
});

I think your problem might be related to you not ending the request in your server's code. After doing the modifications in your db, you should send a response to your front-end, if not it might try to repeat the request and you would end up with your endpoint being called two times.

Try something like:

app.post("/addCases", function(req, res){

    user.find({user: req.body.user}, async function(err, doc) {

        if(err) {
            console.log(err);
        } else {

            for (const iterator of req.body.list) {

                await user.updateOne({user: req.body.user},
                    { $push: {cases: iterator}}, {useFindAndModify: false}, function(err, raw) {
                        if(err) {
                            console.log(err);
                        } else {
                            console.log(value + ' <----- Value');
                    }
                });
            }
        }
        // New code
        res.json({ ok: true });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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