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.

10
  • Have you tried to put you code inside : mongoose.connection.on('open') function callback? Commented Mar 8, 2016 at 14:29
  • BTW, your Timer require is: require('./../../models/timer') or require('../models/timer') ? Commented Mar 8, 2016 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 Commented Mar 8, 2016 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 Commented Mar 8, 2016 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 Commented Mar 8, 2016 at 14:45

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

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.
You cannot make client side Javascript and server side Javascript coexist at the same file.
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
I posted a Sample app to my answer! It is a good way to start.
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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.