I am new to nodejs and am trying to code a quiz. Now I am able to fetch questions from collections usingdb.collection.find()
but my problem is I do not want to display all data(i.e. quiz questions) at once on the page. What I want is that I will display the first question and then when the user will click 'NEXT' button then the next question will be displayed.
Like say if there are 10 questions then at first only one question will be displayed and then when user clicks on 'NEXT' button then the second question will be displayed and so on.
I am short of ideas as to how to implement it.Please help.
Here is the relevant code from app.js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, QuizProvider = require('./quizprovider').QuizProvider;
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {layout: false});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
var qProvider= new QuizProvider('localhost', 27017);
//Routes
......
......
//index
app.get('/', function(req, res){
qProvider.findAll(function(error, ques){
res.render('index', {
title: 'Questions',
myquiz:ques
});
});
});
app.listen(process.env.PORT || 3000);
Here is the relevant code from quizprovider.js
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
QuizProvider = function(host, port) {
this.db= new Db('quiz-db', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
.......
.......
//find all questions
QuizProvider.prototype.findAll = function(callback) {
this.getCollection(function(error, quiz_collection) {
if( error ) callback(error)
else {
quiz_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
exports.QuizProvider = QuizProvider;
Here is the index.jade
extends layout
block content
h1= title
#Questions
- each mq in myquiz
div.mq
div.Question= mq.Question
a(href="/question/new")!= "Add New Question"
Ok friends I finally found a way to solve this problem. First I retrieved the records from myquiz
to an array called data
using Javascript in the JADE end and then displayed it using the following Jquery code in the JADE template:
$( "#myquestions" ).html(data[0]);
$( "#option1" ).html(data[1]);
$( "#option2" ).html(data[2]);
$( "#option3" ).html(data[3]);
$( "#option4" ).html(data[4]);