Nodejs, Mongodb and Promises

1

I need to know how to execute Nodejs in a correct and orderly way:

  
  • Connect with Mongo.
  •   
  • Execute query (Insert, Select, Update, Delete)
  •   
  • Return results
  •   
  • Close connection.
  •   

    My idea is that whenever you need to make a query, call the connection, run the query and return the data and close it (so you would have the possibility to make many queries using a single connection). Following the manual of Mongodb I did the following but I do not know how to order myself:

    var MongoClient = require('mongodb').MongoClient;
    
    var url = 'mongodb://localhost:27017/miConeccion';
    function ConectarMongo(){
    var promesa = new Promise(function(resolve, reject) {
            MongoClient.connect(url, function(err, db) {
                if(err){
                    reject(err);
                    return;
                }
                resolve(db)
            });
    });
    return promesa;
    }
    
    var conexion = ConectarMongo();
    conexion.then(
        function(db){
            return db;
        },
        function(err){
            console.log("Hemos fallado en la conexión");
        }
    );
    
        
    asked by Ricky 16.05.2017 в 07:17
    source

    1 answer

    2

    Lately I'm answering my own questions, well here's the solution, I've already testified:

    var MongoClient = require('mongodb').MongoClient;
    
    var url = "mongodb://localhost:27017/miConeccion";
    
    var Conectar = function(){
    return new Promise( function( resolve, reject ) {
        MongoClient.connect(url, function( err, db ) {
            if(err) reject(err);
            db.collection("usuarios").findOne({}, function(err, result){
                // console.log( result )
                resolve(result);
                db.close();
            });
        });
    });
    }
    
    Conectar()
    .then(function( result ) {
        console.log( result );
    });
    

    My source was the following answer: link

    I hope you serve someone.

        
    answered by 16.05.2017 в 17:44