NodeJS et MongoDB : requête « JOIN » fonctionnelle

// Exemple copié collé et adapté sur stackoverflow :              
// http://stackoverflow.com/questions/15630770/node-js-check-if-path-is-file-or-directory
// http://stackoverflow.com/questions/7268033/basic-static-file-server-in-nodejs 
//                                                                               
var http = require('http'),                                            
    url = require('url'),                          
    fs = require('fs'),                            
    mongoose = require('mongoose'),                
    fileSystem = require('fs'),                    
    path = require('path');                        
var mimeTypes = {                                                                
    "html": "text/html",                 
    "jpeg": "image/jpeg",                
    "jpg": "image/jpeg",                 
    "png": "image/png",                  
    "js": "text/javascript",             
    "css": "text/css"};                  
                                                                                 
var server;                                                                      
var Schema = mongoose.Schema;                                                    
                                                                                 
mongoose.connect('mongodb://localhost/test');                          
var db = mongoose.connection;                                                    
                                                                                 
var creneauSchema = new Schema({                                                 
    libelle:    String,                                      
    date_debut: { type: Date, default: Date.now },           
    date_fin:   { type: Date, default: Date.now },           
    heure_debut: Number,                                     
    duree: Number,                                           
    creneauxJours_id: { type: Schema.Types.ObjectId, ref: 'CreneauJours' }
});                                                                              
var Creneau = db.model('Creneau', creneauSchema);                      
                                                                                 
var creneauJoursSchema = new Schema({                                            
    jours_semaine: [Number]                                  
});                                                                              
var CreneauJours = db.model('CreneauJours', creneauJoursSchema);       
                                                                                 
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {                                          
    console.log('DB connexion reussie');           
    //var cj = new CreneauJours({                            
    //    jours_semaine: [1,2,3,4,5]                         
    //});                                                    
    //cj.save(function (err) {                               
    //    if (err) { return console.log(err); }              
    //    console.log('Écriture réussie');
    //    var c = new Creneau({                              
    //        libelle: "Après midi à 16 heures",
    //        date_debut: new Date(2010, 1, 1),              
    //        date_fin:   new Date(2020, 1, 1),              
    //        heure_debut: 16,                               
    //        duree: 120,                                    
    //        creneauxJours_id: cj._id                       
    //    });                                                
    //    c.save(function (err) {                            
    //        if (err) { return console.log(err); }          
    //        console.log('Écriture 2 réussie');
    //    });                                                
    //});                                                    
    //return;                                                
                                                                                 
    server = http.createServer(function (request, response) {
        if (request.url=='/creneaux') {
            console.log("> JSON");
            Creneau  
            .find({})
            .select('_id libelle date_debut date_fin heure_debut duree creneauxJours_id')
            .populate('creneauxJours_id')
            .exec(function (err, c) {
                if (err) {
                    return console.log(err);
                }
                console.log(c);
                var retour='[';
                for (var i = 0; i < c.length; i++) {
                    retour += '{'
                        + 'id:' + JSON.stringify(c[i]._id)+', '
                        + 'libelle:' + JSON.stringify(c[i].libelle)+', '
                        + 'date_debut:' + c[i].date_debut+', '
                        + 'date_fin:' + c[i].date_fin+', '
                        + 'heure_debut:' + c[i].heure_debut+', '
                        + 'duree:' + c[i].duree+', '
                        + 'jours:[' + c[i].creneauxJours_id.jours_semaine + ']'
                        + '},';
                };
                /* Enlever la dernière virgule : */
                retour=retour.substr(0, retour.length-1)+']';
                response.writeHead(200, {
                    'Cache-Control': 'no-cache, must-revalidate',
                    'Expires': 'Mon, 26 Jul 1997 05:00:00 GMT',
                    'Content-type': 'application/json'
                });
                response.end(retour);
            });      
            // Stopper tout traitement :
            return;  
        }                                
        var uri = url.parse(request.url).pathname;
        var filename = path.join(process.cwd(), uri);
        console.log("> " + filename);
        fs.exists(filename, function(exists) {
            if ((!exists) || (fs.lstatSync(filename).isDirectory())) {
                console.log(">> fichier inexistant : " + filename);
                response.writeHead(200, {'Content-Type': 'text/plain'});
                response.write('404 Not Found\n');
                response.end();
                // Stopper tout traitement :
                return;
            }        
            var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
            response.writeHead(200, {'Content-Type':mimeType});
                                                                                 
            var fileStream = fs.createReadStream(filename);
            fileStream.pipe(response);
        });                              
                                                                                 
    });                                                      
    // Listen on port 8000, IP defaults to 127.0.0.1         
    server.listen(8000);                                     
    // Put a friendly message on the terminal                
    console.log("Server running at http://127.0.0.1:8000/");
});

Poster un commentaire

Vous devriez utiliser le HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>