简体   繁体   中英

Is this the optimal way to perform operations to MongoDB through a node.js?

I've writen this code where I start a connection to my MongoDB server and inside such connection I perform the web services code.

Is this an optimal or safe way? What would be better ways to implement this?

var express = require("express");
var mongodb = require("mongodb");
var servidor = new express();

var BSON = mongodb.BSONPure;
servidor.use(express.static(__dirname+"/publico"));
servidor.use(express.bodyParser());
var cliente_mongodb = mongodb.MongoClient;

cliente_mongodb.connect("mongodb://localhost/db_escuela", function(err, db_escuela){
    if(err){
        console.log("Error de conexion"+err);
    }else{
        console.log("Se ha conectado a la base de datos");
        var cl_alumnos = db_escuela.collection("cl_alumnos");

        servidor.get("/alumnos",function(peticion, respuesta){
            cl_alumnos.find().toArray(function(err,respuesta_db){
                respuesta.send(respuesta_db);
            });
        });

        servidor.get("/alumnos/:id",function(peticion,respuesta){
            var id = new BSON.ObjectID(peticion.params.id);
            cl_alumnos.findOne({'_id':id},function(err,respuesta_db){
                respuesta.send(respuesta_db);           
            });
        });

        servidor.post("/alumnos",function(peticion,respuesta){
            var nuevo_alumno={
                nombre:peticion.body.nombre,
                edad:peticion.body.edad,
                promedio:peticion.body.promedio
            };
            cl_alumnos.insert(nuevo_alumno,function(err,respuesta_db){
                console.log("Se ha insertado: "+JSON.stringify(respuesta_db));
                respuesta.send(respuesta_db);           
            });
        });

        servidor.delete("/alumnos/:id",function(peticion,respuesta){
            var alumno_eliminar = {
                _id : new BSON.ObjectID(peticion.params.id)
            }

            cl_alumnos.remove(alumno_eliminar,function(err,respuesta_db){
                if(err)
                    console.log("No se ha podido eliminar el registro");
                else
                    respuesta.send("Registro Eliminado");               
            });         
        });

        servidor.put("/alumnos/:id",function(peticion,respuesta){
            var id_editado={
                _id : new BSON.ObjectID(peticion.params.id)         
            };
            var alumno_editado={
                nombre:peticion.body.nombre,
                edad:peticion.body.edad,
                promedio:peticion.body.promedio
            };      
            cl_alumnos.update(id_editado, alumno_editado, function(err, respuesta_db){
                if(err)
                {
                    console.log("Error:"+err);
                }
                else
                {
                    console.log("Resultado "+respuesta_db);
                    respuesta.send("Actualizacion Exitosa");
                }
            });
        });


        servidor.listen(8080,function(){
            console.log("El servidor esta escuchando en el puerto 8080");
        });             
    }


});

This is fine, and safe. The connection to MongoDB is only made once. You are adding anonymous functions with a reference to this connection to the middleware for your server.

As far as code organization goes, some may suggest breaking this up a bit. For an application of the size above, I see no problem. If you plan to grow, some refactoring may be warranted.

Please don't be afraid to use ODM like Mongoose. It more easier than you think and will solve any problems you have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM