update a document in mongodb using mongoose

Refresh

April 2019

Views

58 time

1

I'm trying to update a collection in mongodb using mongoose.

function check (db) {

    var hours = 60 * 60 * 1000
    var threeHours = 3 * hours;

    var lastUpdated = null;

    db.collection("profile").find({userName: "Rick"}).toArray(function(err, result){

        var results = result[0]
        var currentTime = new Date().getTime();
        lastUpdated = new Date(results.lastUpdated).getTime();
        var totalPoints = results.points.free + results.points.purchased;

        var timeSinceLastUpdate =  currentTime - lastUpdated;


        // console.log(timeSinceLastUpdate)
        if (timeSinceLastUpdate >= threeHours) {
            // ... time to update score ... 
            if(totalPoints < 200){
                results.free += 50; // issue 50 free points
                db.collection("profile").insert({
                    points: {
                        free: results.free
                    }
                }, function(err, res){
                    if(err) throw err;

                    console.log(res)
                })
        } else { 
            // do nothing, wait for next check  

        }

    })

console says

{ result: { ok: 1, n: 1 },
  ops: [ { points: [Object], _id: 5b2091161dc9ac7f916ec67f } ],
  insertedCount: 1,
  insertedIds: { '0': 5b2091161dc9ac7f916ec67f } }

But the actual database doesn't get updated .. please correct me what I'm doing wrong here.

Any help would be greatly appreciated.


EDIT: Here is my model

var mongoose = require('mongoose');

var profileSchema = new mongoose.Schema({
    userName: String,
    points: {
        free: Number,
        purchased: Number
    },
    itemsPurchased: [{
        name: String
    }],
    itemsAvailable: [{
        name: String,
        points: Number
    }],
    accountCreated: { // for initializing 3 hours check
        type: Date,
        default: Date.now
    },
    lastUpdated: { // check every 3 hours for issuing free points
        type: Date,
        default: Date.now
    }
}, {
    collection: 'profile',
    strict: 'throw'
});

var Profile = mongoose.model('Profile', profileSchema);

module.exports = Profile;

I've updated the post with my model as well, Is my model/schema relevant to my db.insertions?

1 answers

1

Your answer

var moment = require('moment');
var Profile = require('./model/profile.js');
var threeHours = 10800000;//3 hours in millisecs
Profile.findOne({ userName: "Rick" }, function (err, result) {
    var nowDate = new Date();
    var currentTime = moment(nowDate);
    var lastUpdated = moment(result.lastUpdated);
    var TotalDuration =  Math.abs(moment.duration(currentTime.diff(lastUpdated)));//value in millisec
var totalPoints = result.points.free + result.points.purchased;
// console.log(timeSinceLastUpdate)
if (TotalDuration >= threeHours) {
    // ... time to update score ... 
    if (totalPoints < 200) {
        result.free += 50; // issue 50 free points
        Profile.update(
            {
                userName: "Rick"
            },
            {
                $set: {
                    points: {
                        free: result.free
                    }
                }
            },
            function (err, res) {
                if (err) throw err;
                console.log(res)
            })
    } else {
        // do nothing, wait for next check  
    }
}
})

refer moment

install moment by ( npm install --save moment)