These are chat archives for Automattic/mongoose

18th
Jun 2016
Alex Shpak
@ishikawayoshi
Jun 18 2016 18:14
hi, all. Can you tell me what is the best way to do with mongoose next steps.
I need to fetch from database all documents, in document i have date field which i need to compare with current date and next i need to add number of difference between this dates in other field of this document.
Alex Shpak
@ishikawayoshi
Jun 18 2016 18:20
i try to solve it this way, but i think it's not mongoose way
var mongoose = require('mongoose');
var LoanModel = require('./model/Loan');
var timediff = require('timediff');

mongoose.connect('mongodb://localhost/accountant');

LoanModel.find({}, function(err, data) {
    for (var i = 0; i < data.length; i++) {
        var createD = new Date(data[i].date);
        var curD = new Date();
        var diff = timediff(createD, curD).months;
        if (diff > 0) {
            LoanModel.findOne({
                '_id': data[i]._id
            }, function(err, result) {
                if (!result) {
                    console.log('Test test test');
                } else {
                    result.extra_percent = diff;
                    result.save(function(err) {
                        if (err) {
                            console.log('There is an error with ' + data[i]._id);
                        } else {
                            console.log('All is ok with ' + data[i]._id);
                        }
                    })
                }

            })
        }
    }
    mongoose.disconnect();
});
if you give me any reference or advice how to do it better it'll be great
Thanks in advanced.
Daniel Acuña
@moustacheful
Jun 18 2016 18:39
I believe you could solve this using the aggregation framework . I don't know exactly how to solve your particular problem, but you can look into it and see if it helps.
Alex Shpak
@ishikawayoshi
Jun 18 2016 18:40
@moustacheful thanks, i'll check it