0

I have a function called save with this code, it's meant to save data from a timer.

The class with the Model is this:

var Schema = mongoose.Schema;


var Timer = new Schema({
    Time: {type: Number},
    Desc: {type: String},
    Doc: {type: String}
});

Timer.statics.findByDesc = function(value, callback){
    this.find({ Desc: {"$regex": value, "$options": "i"}}, callback);
}

Timer.statics.findByDoc = function(value, callback) {
    this.find({ Doc: { "$regex": value, "$options": "i" }}, callback);
}

Timer.statics.findAll = function(callback){
    this.find({}, callback);
}


module.exports = mongoose.model('Timer', Timer);

the model is defined by this code which is imported with:

var Timer = require('./../../models/timer');

but I'm testing it with constants in a function which is called by clicking button, this is the code inside the function:

var newTimer = new Timer({
    Time: 6000, Desc: "My first timertest!", Doc: "Test's Dossier"
});
newTimer.save();

however with trial and error I have figured out that it never calls newTimer.save(), it seems to get stuck somewhere without ever leaving the var newTimer = new Timer() function. I have tried my Timer Model code in other files with code like:

/**
 * Created by kevin on 08/03/2016.
 */
var Timer = require('../models/timer'),
mongoose = require('mongoose');


mongoose.connect('mongodb://localhost:27017/legalapp');
mongoose.connection.on('open', function() {
    console.log('Mongoose connected.');
});

var newTimer = new Timer({
    Time: 5000, Desc: "My first timertest!", Doc: "Test's Dossier"
});



console.log(newTimer.Time);
console.log(newTimer.Desc);
console.log(newTimer.Doc);
newTimer.save();
mongoose.connection.close();

and this did work, so after 3 hours of trying, I'm going crazy, so I came here. I am using javascript, nodeJS, jquery and mongoose in my project.

Here is the entire file:

var timers = [], Timer = require('./../../models/timer');

function timer(id){
    this.id = id;
    this.running = false;
    this.start = new Date();
    this.current = new Date();
    this.paused = new Date();
    this.timed = 0;
    this.desc = "";
    this.pauseTime = 0;
    this.pauseTimeBuffer = 0;
    this.prevTimed = 0;
    this.first = true;
    this.h = Math.floor(this.timed / 1000 / 60 / 60);
    this.timed -= this.h * 1000 * 60 * 60;
    this.h = checkTime(this.h);
    this.m = Math.floor(this.timed / 1000 / 60);
    this.timed -= this.m * 1000 * 60;
    this.m = checkTime(this.m);
    this.s = Math.floor(this.timed / 1000);
    this.timed -= this.s * 1000;
    this.s = checkTime(this.s);
}

function startTime(timer){
    if(!timer.running) {
        if (timer.first) {
            timer.start = new Date();
            timer.first = false;
        }
        timer.running = true;
        time(timer);
    }
}

function stopTime(timer){
    if(timer.running) {
        if (timer.pauseTime === 0) {
            timer.paused = new Date();
        } else {
            timer.paused = new Date();
            timer.pauseTimeBuffer = timer.pauseTime;
        }
        timer.running = false;
        time(timer);
    }
}

function save(timer){
    //stopTime(timer);
    /*var desc = prompt("Enter the description of this task", timer.desc);
    var dossier = prompt("What dossier does this timer belong to?");
    var current = new Date();
    var timed = timer.current - timer.start;
    timed -= timer.pauseTime;
    */
    var newTimer = new Timer();
    newTimer.Time = 6000;
    newTimer.Desc = "My first timertest!";
    newTimer.Doc = "Test's Dossier";
    newTimer.save();
    alert("yay");
}

function time(timer) {
    if(timer.running) {
        var name = '#timer' + timer.id;
        var $time = $('' + name);
        timer.current = new Date();
        timer.timed = timer.current - timer.start;
        timer.timed -= timer.pauseTime;
        timer.h = Math.floor(timer.timed / 1000 / 60 / 60);
        timer.timed -= timer.h * 1000 * 60 * 60;
        timer.h = checkTime(timer.h);
        timer.m = Math.floor(timer.timed / 1000 / 60);
        timer.m = checkTime(timer.m);
        timer.timed -= timer.m * 1000 * 60;
        timer.s = Math.floor(timer.timed / 1000);
        timer.timed -= timer.s * 1000;
        timer.s = checkTime(timer.s);
        $time.html("" + timer.h + ":" + timer.m + ":" + timer.s);
        //var t = setTimeout(time(timer), 10);
    }else{
        timer.current = new Date();
        timer.pauseTime = timer.current - timer.paused;
        timer.pauseTime += timer.pauseTimeBuffer;
        //var t = setTimeout(time(timer), 10);
    }
}

function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}

function init(timer){
    var name = "#timer" + timer.id;
    var $time = $('' + name)
    $time.html("" + timer.h + ":" + timer.m + ":" + timer.s);
    run();
}

function run(){
        for(i = 0; i < timers.length;i++){
            var timer = timers[i];
            setTimeout(time(timer), 10);
        }
    setTimeout(run, 10);
}

function action(id, action){
    if(action === "start"){
        var t = timers[id - 1];
        startTime(t);
    }else if(action === "stop"){
        var t = timers[id - 1];
        stopTime(t);
    }else if(action === "save"){
        var t = timers[id - 1];
        save(t);
    }
}

function stopAll(){
    for(i = 0; i < timers.length; i++){
       var t = timers[i];
       stopTime(t);
    }
}

function add(){
    stopAll();
    var number = timers.length + 1;
    var starttext = '"start"';
    var savetext = '"save"';
    var stoptext = '"stop"';
    var newTimer = new timer(number);
    timers.push(newTimer);
    $('#timers').append("<br/>" +
        "<h1>Timer " + number + "</h1>" +
        "<div id=" + 'timer' + number + ">Test</div>" +
        "<button onclick='action(" + number + ", " + starttext + ")" + "'>Start</button>" +
        "<button onclick='action(" + number + ", " + stoptext + ")" + "'>Stop</button>" +
        "<button onclick='add()'>Add</button>" +
        "<button onclick='action(" + number + ", " + savetext + ")" + "'>Save</button>" +
        "<p class='description' id='" + 'desc' + number + "'>Click here to enter a description</p>");
    $(".description").click(function(){
        var text = prompt("Please enter your description here");
        if(text === ""||text === null) {
            $(this).html("Click here to enter a description");
        }else{
            $(this).html(text);
            timers[number - 1].desc = text;
        }
    });
    init(newTimer);
    setTimeout(startTime(newTimer));
}

Save is the function that I have problems with.

David Tansey
  • 5,813
  • 4
  • 35
  • 51
Kevin Jansen
  • 59
  • 1
  • 8
  • Have you tried to put you code inside : mongoose.connection.on('open') function callback? – André Bonna Mar 08 '16 at 14:29
  • BTW, your Timer require is: require('./../../models/timer') or require('../models/timer') ? – André Bonna Mar 08 '16 at 14:36
  • The require refers to different files with the same code(except opening a connection which happens elsewhere), i tested in a different folder hence the different files used, i tested using both files and the tests were both succesfull, and no i can't put it inside the connection.open function since the connection is opened in a server.js file and remains open, i am however sure that the connection is open before the function runs – Kevin Jansen Mar 08 '16 at 14:39
  • And the problem is that this exact code works in the test file but not when used in the function that i use when clicked on a button, the function and the button are connected with jquery – Kevin Jansen Mar 08 '16 at 14:40
  • 1
    Please post your jquery code, I don't see how a view button calls a function from backend. You need something like an AJAX call for that – André Bonna Mar 08 '16 at 14:45
  • I posted the entire code, i believe that that should suffice. – Kevin Jansen Mar 08 '16 at 14:49
  • You mentioned a jquery code and a view button. Maybe the problem is in one of this two. Thats the reason why your code work in a test environment. – André Bonna Mar 08 '16 at 14:52
  • Not a view button, but a add button, its just a button that calls the function, nothing more nothing less, and i tested to see if it gets to the function and it does, the problem is that once it gets to: var newTimer = new Timer({ Time: 6000, Desc: "My first timertest!", Doc: "Test's Dossier" }); it doesn't continue any further along and the jquery code is used in the add function which adds a timer to my page. – Kevin Jansen Mar 08 '16 at 14:54
  • I still don't see how a button calls a function from backend. You need something like an AJAX call for that. – André Bonna Mar 08 '16 at 14:56
  • Oh hold on, it doesn't use jquery to call the function, my bad, it uses onclick, it adds timers to the page using jquery, but the function call is done with onclick. – Kevin Jansen Mar 08 '16 at 14:56

1 Answers1

0

You cannot make client side Javascript and server side Javascript coexist at the same file. Jquery/HTML code runs inside a browser and nodejs/express runs inside a server.

Reference to Client-Server concept

https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming


Some good reference to work with NodeJS

calling a server side function from client side(html button onclick) in node.js


Sample app

https://github.com/jmhdez/Nodejs-Sample

Community
  • 1
  • 1
André Bonna
  • 807
  • 8
  • 13
  • The buttons are created by javascript so the button has access to the functions, and the javascript is on the same page as the buttons, and i am using express. – Kevin Jansen Mar 08 '16 at 15:05
  • You cannot make client side Javascript and server side Javascript coexist at the same file. – André Bonna Mar 08 '16 at 15:24
  • 1
    Thank you, i didnt realize that part of my code was server sided (this is my first javascript project) i will try it and tell you if it works – Kevin Jansen Mar 08 '16 at 15:32
  • I posted a Sample app to my answer! It is a good way to start. – André Bonna Mar 08 '16 at 15:35
  • 1
    Yes i have tried, i forgot to reply and this helped me, once you told me that part of it was server sided i managed to solve the problem, thank you very much :) – Kevin Jansen Mar 09 '16 at 17:32