javascript - 如何使用node.js在server.js中传递参数

标签 javascript node.js mongodb express

我想将参数数据从mongoDB传递到服务器端。 我创建了全局变量diagramData以从diagramModel.find()查询传递到app.post函数。但当 console.log(diagramData) 时它是空数组。有人能帮我弄清楚吗?谢谢

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
    });
});

最佳答案

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.

在某个地方写下你的连接并在任何地方使用它

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
        });
      }
    });
  });
});

关于javascript - 如何使用node.js在server.js中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39922824/

相关文章:

javascript - 在 Node 中强制进行垃圾收集以测试 WeakRef 和 FinalizationRegistry

node.js - Node.js 中的应用程序结构?

node.js - 如何从 Mongoose 中删除已定义的架构?

java - 使用 application.yml 中的属性从 spring data mongodb 注入(inject) @Document 中的集合名称

javascript - 显示按钮单击 Angular 2 的详细信息

javascript - 索引页面与 AngularJS 应用程序的其余部分分开?

javascript - jquery 中的 ScrollTo()

node.js - 罗博蒙戈 : Doesn't display all documents

javascript - 如何在 Electron.js 中保存在 Canvas 上绘制的图像

java - MongoDB、Java : Retrieve date property as UTC