1

I want to pass parameters data from mongoDB to server side. And I create global variable diagramData to pass from diagramModel.find() query to app.post function. But it was empty array when console.log(diagramData).Can somebody help me figure it out? Thanks

var diagramData = [];
mongoose.connection.on('connected', function () {
    diagramModel.find({}, function(err, data) {
      diagramData = data;
    });
});

app.post('/display_bpmnFile', function(req, res) {
    console.log(diagramData);
    res.send({
        file: diagramData
    });
});
kun zhang
  • 31
  • 2
  • are you getting the data value? – abdulbarik Oct 07 '16 at 17:31
  • This is not about node and mongo. You need to check how async functions work. [Understanding Async Programming in node.js](https://blog.risingstack.com/node-hero-async-programming-in-node-js/) – Omar A Oct 07 '16 at 17:34
  • You will get any value in any time – abdulbarik Oct 07 '16 at 17:36
  • data value is in json format; data = { "owner" : "sh529u", "text" : "sco_poc.bpmn", "users":["wp6307","kz323j","ew6980"], "groups":[], "string" : "test" } – kun zhang Oct 07 '16 at 17:39

1 Answers1

0

You will not get value in that since when you call your route then it works as async nature so most of the chance your array will be empty.


It's not a proper answer since I am writing your connection in route.

Write your connection in somewhere and use it everywhere

app.post('/display_bpmnFile', function(req, res) {
  mongoose.connection.on('connected', function() {//connection code must not be here put it in somewhere else and make it common
    diagramModel.find({}, function(err, data) {
      if (!err) {
        res.send({
          file: data
        });
      }
    });
  });
});
abdulbarik
  • 6,101
  • 5
  • 38
  • 59