Wednesday 10 May 2017

How to write findone update/insert query using node,express,mongod

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 giftList = [];

for (var i = 0; i < summary.length; i++) {
    var mod = Math.floor(summary[i].balancepoints / 1000);

    for (var j = 0; j < mod; j++) {
        var obj = {
            mobilenumber: summary[i].mobilenumber,
            gifed_id: 1,
            ref: 'gifted',
            gifed_point: 1000,
            active: true
        }
        summary[i].balancepoints -= 1000;
        summary[i].negativepoint -= 1000;
        giftList.push(obj);
    }
    console.log("summarylist = ", summary);
}

if you run above code you will get one object.

here i am trying to insert/update document but its not working.

if mobilenumber is matched in Summary collection document i need to update t

positivepoint

negativepoint

balancepoints

in that particular document .

if mobilenumber is not matched i need to create new document with

positivepoint

negativepoint

balancepoints

for(var i = 0; i<summary.length;i++)
{

Summary.findOne({
            "mobilenumber": summary[i].mobilenumber
        },
        JSON.stringify(obj), {
            upsert: true
        },
        function(err, Summary) {
            if (err) {
                console.warn(err.message);
            } else {
                console.log(obj);
            }
        }
    )
}

i written query but its not working...



via its me

No comments:

Post a Comment