i am making a website that needs to change a embedded video when a button is clicked. My html page loads a js script that needs to call a function in the database which was coded with node. The whole thing is running on a mongoDB server with mongoose to back me up. To make things more clear here is some code:
My database (only the relevant functions):
function database(){
db = mongoose.createConnection(url);
songModel = db.model('Song',{id : Number ,
title : String,
artist : String,
genre : String,
rating : Number,
link : String
});
//init freeid
songModel.count({},function(err, c){
nextFreeId=c;
});
};
database.prototype.getNextFreeId = function(){
return nextFreeId;
};
database.prototype.getSongById=function(id2){
songModel.findOne({id : id2}, function(err,obj){
if (err) {
console.log('Not Found, error: '+err);
return null;
} else if (obj) {
console.log('Found:', obj);
return obj;
}
});
};
module.exports = database;
Now i need to call a script via my html page that is able to call the getSongById(someID). How should i be doing that knowing i can't require(database) because require is node and server based. Also since getSongById(someID) is asynchronous because of the save call how do i make sure the return value is not null? Do i need to timeout a couple of secs?
The script file would need to be something like this and the html page loads getRandomVideo() :
var db=require('./module/database');
function getRandomVideo(){
console.log('random video method called');
var numberOfSongs = db.getNextFreeId()-1;
idToGet=Math.floor(Math.random() * numberOfSongs);
var song = db.getSongById(idToGet);
document.getElementById('myVideo').src = song.link;
console.log('found random song: '+ song);
}
Thanks you for the help!
EventEmitter2. Then make it an interface and implement it differently for server and client. So that client callsdb.getSongById(666, (result)=>{})where(result)=>{}is callback that handles the result once it comes from the server. This is how it's properly done.