Friday 9 June 2017

mongoose queries are not executing orderly [duplicate]

This question already has an answer here:

I am using nodejs and mongoose, in a file i am trying to execute two find() queries. In the second query i am using the result of first query but i think the second query is executing first or something else is happening which i dont understand. My code is as below:

 var express = require('express');
    var morgan = require('morgan');
    var moment=require('moment');
    var fs=require('fs');
    var mongoose = require('mongoose');
    var Match= require('./Match');// schema
    var Info = require('./Info');// schema

    var bodyparser = require('body-parser');
    var app = express();
    app.use(morgan('dev'));
    var crypto = require('crypto');
    var cl;
    var cn;
    var x;


    var Base64Id = function() { };

    Base64Id.prototype.getRandomBytes = function(bytes) {



      var BUFFER_SIZE = 4096
      var self = this;  

      bytes = bytes || 12;

      if (bytes > BUFFER_SIZE) {
        return crypto.randomBytes(bytes);
      }

      var bytesInBuffer = parseInt(BUFFER_SIZE/bytes);
      var threshold = parseInt(bytesInBuffer*0.85);

      if (!threshold) {
        return crypto.randomBytes(bytes);
      }

      if (this.bytesBufferIndex == null) {
         this.bytesBufferIndex = -1;
      }

      if (this.bytesBufferIndex == bytesInBuffer) {
        this.bytesBuffer = null;
        this.bytesBufferIndex = -1;
      }

      // No buffered bytes available or index above threshold
      if (this.bytesBufferIndex == -1 || this.bytesBufferIndex > threshold) {

        if (!this.isGeneratingBytes) {
          this.isGeneratingBytes = true;
          crypto.randomBytes(BUFFER_SIZE, function(err, bytes) {
            self.bytesBuffer = bytes;
            self.bytesBufferIndex = 0;
            self.isGeneratingBytes = false;
          }); 
        }

        // Fall back to sync call when no buffered bytes are available
        if (this.bytesBufferIndex == -1) {
          return crypto.randomBytes(bytes);
        }
      }

      var result = this.bytesBuffer.slice(bytes*this.bytesBufferIndex, bytes*(this.bytesBufferIndex+1)); 
      this.bytesBufferIndex++; 

      return result;
    }

    /**
     * Generates a base64 id
     *
     * (Original version from socket.io <http://socket.io>)
     */

    Base64Id.prototype.generateId = function () {


    console.log("n");
// my first query
    Match.matching.find({}, function (err, mat) {
           console.log("s");
            if (err) 
              return console.log("error");

            //response.json(infos);
            if(mat.length){
              console.log("nnn");
                h=0;
           console.log(mat[0].toObject().name); 
           cn=(mat[0].toObject().name);
        }
        });

    console.log("nn");

    if(h==0){
      console.log("name"+cn);
      h++;
    //my second query
    Info.inform.find({"name":cn}, function (err, inf) {
           console.log("ss");
            if (err) 
              return console.log("error");
          console.log(inf);
            if(inf.length){
              console.log("sss");
              x=0;
              console.log(inf[0].toObject().link);
              cl=inf[0].toObject().link;
          }

        }).select({"link": 1, "_id": 0});

    }

    if(x==0)
    {

      x++;
     console.log("in base"+cl);
      return cl;
      }

    else if(x!=0)
    {
      var rand = new Buffer(15); // multiple of 3 for base64
      if (!rand.writeInt32BE) {
        return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()
          + Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();
      }
      this.sequenceNumber = (this.sequenceNumber + 1) | 0;
      rand.writeInt32BE(this.sequenceNumber, 11);
      if (crypto.randomBytes) {
        this.getRandomBytes(12).copy(rand);
      } else {
        // not secure for node 0.4
        [0, 4, 8].forEach(function(i) {
          rand.writeInt32BE(Math.random() * Math.pow(2, 32) | 0, i);
        });
      }

    return rand.toString('base64').replace(/\//g, '_').replace(/\+/g, '-');
    }
    };

     exports = module.exports = new Base64Id();

If i first query returns something in the result then i making h=0, then if h=0 the second query need to be executed. If my second query returns something in the result then i make x=0 and if x=0 the id obtained as a result of second query need to be returned or the new id need to be returned.

The actual output in the console need to be as:

n
s
nnn
1000
nn
name1000
ss
sss
B_VfTceWRWyqC0DHACBD
in baseB_VfTceWRWyqC0DHACBD
B_VfTceWRWyqC0DHACBD joined// this output will be generated from another file
B_VfTceWRWyqC0DHACBD ready to stream//this output will be generated from another file

I am giving all the true cases, but i am getting the output as:

n
nn
-- V6_mcwH2edz52pAGAAAA joined --
s
nnn
1000
-- V6_mcwH2edz52pAGAAAA is ready to stream --

It shows that my queries are not executing orderly. I am new to this concept i am understanding how to get out of these problem.



via Gousia

No comments:

Post a Comment