Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 831
its me Avatar asked May 12 '17 13:05

its me


People also ask

What is Upsert true in mongoose?

In MongoDB, an upsert means an update that inserts a new document if no document matches the filter . To upsert a document in Mongoose, you should set the upsert option to the Model.

How do you update Upsert?

Or in other words, upsert is a combination of update and insert (update + insert = upsert). If the value of this option is set to true and the document or documents found that match the specified query, then the update operation will update the matched document or documents.

What is Upsert true in MongoDB?

Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter. In that case, the applied update operation will update the documents. If the value is true and no documents match the condition, this option inserts a new document into the collection.

How do I update my mongoose?

There are multiple ways to update documents in Mongoose. You can either use the save() , updateOne() , updateMany() , or findOneAndUpdate() method.


2 Answers

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.

like image 193
Mykola Borysyuk Avatar answered Sep 19 '22 13:09

Mykola Borysyuk


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

                    });

            });



        });
    }
like image 27
its me Avatar answered Sep 18 '22 13:09

its me