-1

When i click ctr + r sometimes the whole data doesn't show up. on my ("/") page I have a left side and a right side. The left side should display all of the data and the right side should display a random piece of data. It works most of the time but if I click ctr + r on the keyboard to refresh sometimes some or all the data doesn't appear .

This is how my code works.

  • sets the comps collections to the data from arr (now I have 3 elems. 3 docs).
  • Actually before it does that it deletes all the content from the collection so every time I go to "/" I get only 3 docs (for testing)
  • find all docs with the filters and display them on the left side (I can display them because the find method returns doc) then I use doc in the render.
  • use the findOne() to get the random.

Also you should note that I do have the console.log() in my code and that consoles the correct information. I get all 3 documents in the console.

To be honest I never used more than one method on the model when rendering and I never used a random method in a model method. so I maybe messing that up.

I want to know why sometimes the data doesn't appear when I refresh.

server.js

var express = require("express"),
    app = express(),
    mongoose = require("mongoose"),
    ejs    = require("ejs");
mongoose.connect("mongodb://localhost/comp1");
var port = process.env.PORT || 3000;   
app.set("view engine", "ejs"); 
app.use(express.static("./public"));

var Comp = require("./models/company.js");

app.get("/", function(req, res){
    var arr = [
    {name : "comp1",industry : "industry1", ranking: 20},
    {name : "comp2",industry : "industry2", ranking: 5},
    {name : "comp3",industry : "industry3", ranking: 10}
    ]
 Comp.count({}, function(err, count){
       var random = Math.floor(Math.random() * count);
        Comp.find({}).remove({}, function(){
            console.log("removed")
        })
        Comp.create(arr, function(err, docs){
            console.log(docs)
            console.log(count)
        })

       Comp.find({}, 'name -_id ranking', {sort :{ranking :1}}, function(err, doc){
            if(err) throw err;
            Comp.findOne().skip(random).exec(function(err, result){
                res.render("index",{data : doc , count: random , result : result})
            })

        })
   })

})




app.listen(port, function(){
    console.log("node is listening on port : " + port );
})

index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <link rel="stylesheet" href="/style.css">
</head>
<body>
    ontop
    <div class="container clearfix">
        <div class="leftSide">TEST
            <%= data%>
            <%data.forEach(function(comp){%>
                <div><%= comp.name %> <span>ranking : <%= comp.ranking %></span></div>
            <%  }); %>
        </div>
        <div class="rightSide">side <%= count %>
            <div><%=result %></div>
        </div>
    </div>

</body>
</html>

company.ejs

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var compSchema = new Schema({
    name : String,
    industry: String,
    ranking : Number,
    created_at : Date,
    updated_at : Date,
    inc : Number

});

compSchema.pre("save", function(next){
    var currentDate = new Date();
    this.updated_at = currentDate;
    var counter = 0;
    this.inc = counter;
    counter++;

    if(!this.created_at){
        this.created_at = currentDate;
    }
    next();
})

var Comp = mongoose.model("Comp", compSchema);

module.exports = Comp;
jack blank
  • 5,073
  • 7
  • 41
  • 73
  • You are using asynchronous code synchronously. This will never work the way you expect it. Just find some examples how to do multiple DB queries and I think you find your answer – Molda May 18 '16 at 18:10
  • would promises help me here? this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise? I didn't want to have to learn this. – jack blank May 18 '16 at 18:54
  • The methods like `findOne` are synchronous? and I'm using that in a callback which is messing me up so I should use something like .then() is that what is messing up? – jack blank May 18 '16 at 19:02

1 Answers1

1

The simplest but NOT RECOMMENDED way to do what you want would be the code bellow but it usually leads to callback hell or Pyramid of doom and its hard to read so don't use this!!!!

Comp.count({}, function(err, count){
   Comp.find({}).remove({}, function(){
      Comp.create(arr, function(err, docs){
         Comp.find({}, ..., function(err, doc){                
            Comp.findOne().skip(random).exec(function(err, result){
                res.render("index",{})
            })    
         }) 
      })
   })    
})

another way could be to use async.js

async.series([
    function(callback){
        Comp.count({}, function(err, count){
            callback(null, count);
        });
    },
    function(callback){
        Comp.find({}).remove({}, function(){
            callback(null);
        });
    },
    function(callback){
        Comp.create(arr, function(err, docs){
            callback(null);
        });
    },
    function(callback){
        Comp.find({}, ..., function(err, doc){ 
            callback(null);
        });
    },
    function(callback){
        Comp.findOne().skip(random).exec(function(err, lastResult){
            callback(null, lastResult);
        });
    }
],
// optional callback, results is an array of results from each callback if any
function(err, results){
    // results is now equal to [count, lastResult]
    res.render("index",{})
});

and finally Promises I haven't tried or used this, so not 100% sure but something like this

var promise = Comp.count({}).exec();

promise.then(function(count) {
    return Comp.find({}).remove({}).exec();
})
.then(function() {
    return Comp.create(arr, ).remove({}).exec();
})
.then(function() {
    return Comp.find({}).remove({}).exec();
})
.then(function() {
    return Comp.find({}).skip(random).exec();
})
.then(function(result) {
    res.render("index",{})
})

Have a look here for some more details about promises on mongoose How to use mongoose Promise - mongo

Community
  • 1
  • 1
Molda
  • 5,619
  • 2
  • 23
  • 39
  • Thanks for your answer. I wrote a question about `return Model.create(arr).exec()`. that doesn't work. maybe you have some input on this. http://stackoverflow.com/questions/37309637/return-model-createarr-exec-is-not-working-in-mongoose – jack blank May 18 '16 at 20:46
  • I don't think that was the problem http://stackoverflow.com/questions/37313905/when-i-refresh-the-page-sometimes-the-sorted-data-is-not-available – jack blank May 19 '16 at 05:52