admin管理员组

文章数量:1326337

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);
    
}

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

Share Improve this question edited May 15, 2017 at 10:02 its me asked May 12, 2017 at 13:04 its meits me 5426 gold badges30 silver badges67 bronze badges 9
  • 1 Possible duplicate of What is the difference between synchronous and asynchronous programming (in node.js) – Mykola Borysyuk Commented May 12, 2017 at 13:06
  • 1 Also take a look at async module. github./caolan/async . It will help. – Mykola Borysyuk Commented May 12, 2017 at 13:06
  • 1 JSON.stringify(obj) isn't right. – robertklep Commented May 12, 2017 at 13:07
  • Don't use JSON.stringify(). Pass your object directly i.e. obj – Mohit Bhardwaj Commented May 12, 2017 at 13:09
  • Guys he use sync FOR to run async DB operations.. Which will lead to very big problems in future. So JSON.stringify may work here, but still code need to be re-write in async way, using promises or async module. – Mykola Borysyuk Commented May 12, 2017 at 13:10
 |  Show 4 more ments

2 Answers 2

Reset to default 5

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./manual/reference/method/db.collection.update/ Mongo updateOne docs https://docs.mongodb./manual/reference/method/db.collection.updateOne/

Promises https://developer.mozilla/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./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.

 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);
                        }

                    });

            });



        });
    }

本文标签: javascriptupdate with upsert true is not updating in expressmongooseStack Overflow