its me
its me

Reputation: 542

update with upsert: true is not updating in express,mongoose?

var logs = [{
    mobilenumber: '1',
    ref: 3,
    points: 1000,
    ctype: 'mycredit',
    entry: 'sdfsdf',
    entry: 0
}, {
    mobilenumber: '1',
    ref: 6,
    points: 2000,
    ctype: 'mycredit',
    entry: 'sdfsdf',
    entry: 0
}, {
    mobilenumber: '2',
    ref: 7,
    points: 2600,
    ctype: 'mycredit',
    entry: 'sdfsdf',
    entry: 0
}, {
    mobilenumber: '2',
    ref: 15,
    points: -1500,
    ctype: 'mycredit',
    entry: 'sdfsdf',
    entry: 0
}, {
    mobilenumber: '10',
    ref: 15,
    points: 800,
    ctype: 'mycredit',
    entry: 'sdfsdf',
    entry: 0
}, {
    mobilenumber: '11',
    ref: 15,
    points: 110,
    ctype: 'mycredit',
    entry: 'sdfsdf',
    entry: 0
}];

var summary = [];
var positive = 0,
    negative = 0,
    total = 0,
    count = 0;
for (var i = 0; i < logs.length; i++) {
    count = 0;
    positive = 0;
    negative = 0;
    total = 0;

    for (var j = i; j < logs.length; j++) {
        if (logs[i].mobilenumber === logs[j].mobilenumber) {
            if (logs[j].points < 0) {
                negative += logs[j].points;
            } else if (logs[j].points >= 0) {
                positive += logs[j].points;
            }

            total += logs[j].points;
            count++;
        }
    }
    i += count - 1;
    var obj = {
        mobilenumber: logs[i].mobilenumber,
        positivepoint: positive,
        negativepoint: negative,
        balancepoints: total
    }
    summary.push(obj);
    
}

if you run above code you will get Summary objects

in below code i am trying to insert/update code but insert is working but its not updating

var promiseArr = [];
for(var i = 0; i<summary.length;i++) {
    promiseArr.push(saveOrUpdate(summary[i].mobilenumber, summary[i]));
}


function saveOrUpdate (phone, dataToUpdate) {
   return new Promise((resolve, reject) => {
    //Update document if found or insert otherwise
    // upsert:true -> If set to true, creates a new document when no document matches the query criteria

        Summary.update({"mobilenumber": phone}, 
            dataToUpdate,
            {upsert: true}, 
            function(err, raw){
                if (err)
                {
                    console.log(err);
                }else
                {
                    console.log(raw);
                }

            });
   });
}

Here i am trying to insert or update Summary object in Summary collection .

i am searching mobilenumber in Summarycollection if mobilenumber already exsist i am updating that document otherwise ,i am creating new document for that mobilenumber

insert is working but if mobilenumber already ther in summary collection its not updating

help me out i m trying since three days

i am using mongoose and database mlab version 3.2.11

Upvotes: 7

Views: 2555

Answers (2)

its me
its me

Reputation: 542

 var promiseArr = [];
    for (var i = 0; i < summary.length; i++) {
        promiseArr.push(saveOrUpdate(summary[i].mobilenumber, summary[i]));
    }


    function saveOrUpdate(phone, dataToUpdate) {
        return new Promise((resolve, reject) => {

            //Update document if found or insert otherwise
            // upsert:true -> If set to true, creates a new document when no document matches the query criteria
            Summary.findOne({
                "mobilenumber": phone
            }, function(err, data) {
                var newSummary = dataToUpdate;
                console.log(data);
                console.log(newSummary);
                if (data) {
                    newSummary.negativepoint += data.negativepoint;
                    newSummary.positivepoint += data.positivepoint;
                    newSummary.balancepoints += data.balancepoints;
                }
                Summary.update({
                        "mobilenumber": phone
                    },
                    dataToUpdate, {
                        upsert: true
                    },
                    function(err, raw) {
                        if (err) {
                            console.log(err);
                        } else {
                            console.log(raw);
                        }

                    });

            });



        });
    }

Upvotes: 4

Mykola Borysyuk
Mykola Borysyuk

Reputation: 3411

So first take a look at this. What is the difference between synchronous and asynchronous programming (in node.js) . Don't ever use sync and async operations in same place without full understanding what's going on.

Let's try to rewrite your code using async approach. First let's create promise method

function saveOrUpdate (phone, dataToUpdate) {
   return new Promise((resolve, reject) => {
    //Update document if found or insert otherwise
    // upsert:true -> If set to true, creates a new document when no document matches the query criteria
       Summary.updateOne({"mobilenumber": phone}, 
            {$set : dataToUpdate}, 
            {upsert: true}, 
            function(err){
                  err ? reject(err) : resolve();
            });
   });
}

Now just make array of promises

var promiseArr = [];
for(var i = 0; i<summary.length;i++) {
    promiseArr.push(saveOrUpdate(summary[i].mobilenumber, summary[i]));
}

Run promises using Promise.All and catch results.

Promise.all(promiseArr)
.then((res) => console.log("All done"))
.catch(err => console.log(err));

Mongo update docs https://docs.mongodb.com/manual/reference/method/db.collection.update/ Mongo updateOne docs https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/

Promises https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

if you using mongoose as a driver. Read docs to see how you can update document by query. http://mongoosejs.com/docs/2.7.x/docs/updating-documents.html

Mongo DB native driver allows you to use all new mongo features and methods. http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html

Hope this helps.

Upvotes: 5

Related Questions