Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 作用域:如何从查询中调用找到的数据?_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 作用域:如何从查询中调用找到的数据?

Node.js 作用域:如何从查询中调用找到的数据?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我试图在数组外部调用已建立的变量,但它返回一个空数组。有人能解释一下为什么console.log在函数内部工作,而不是在函数外部工作吗 // Video Schema let mongoose = require("mongoose"); let Schema = mongoose.Schema; var videoSchema = new Schema ({ title: String, videoURL: String, author: String,

我试图在数组外部调用已建立的变量,但它返回一个空数组。有人能解释一下为什么console.log在函数内部工作,而不是在函数外部工作吗

// Video Schema
let mongoose =  require("mongoose");

let Schema = mongoose.Schema;

var videoSchema = new Schema ({
  title: String,
  videoURL:  String,
  author: String,
  time: String,
  viewcount: Number,
  categories: [{
    type: Schema.Types.ObjectId,
    ref: "Category"
  }],
    description: String,
})

let Video = mongoose.model("Video", videoSchema);

module.exports = {
  videoSchema: videoSchema,
  Video: Video
}
app.js

let Video = require(__dirname + "/dbs/Video.js").Video;

 app.get("/", function(req,res) {
    
    let videos = []
    Video.find(function(err, foundVideo) {
      if (!err) {
        videos = foundVideo.slice(0)
        console.log(videos) // this return me with an object array [{obj1}, {obj2}]
      } else {
        return err
      }
    })
    console.log(videos) // This return an empty array []

}


如何将foundVideos数组存储在videos变量中,以便调用变量global?

执行此操作时:

Video.find(function(err, data) {
  // something
  console.log("one")
})
// nothing
console.log("two")
括号之间的函数是
find()
操作的回调。这意味着当find执行结束时,它将被回调,并且它可以在其范围内使用
err
data
参数。它将执行
console.log(“一”)

这种“等待”结果的方式是由于js的异步特性

相反,回调方法之外的代码将在调用查找后立即触发,并且不会等待查找操作完成。因此,在本例中,
2
将在
1
之前打印

在您的示例中,您尝试在回调方法
控制台之外打印的变量
videos
。日志(videos)
为空,就像在
视频实际存在之前打印的一样

您应该在
中编写所有回调代码!错误
案例:

if (!err) {
  videos = foundVideo.slice(0)
  console.log(videos) // this return me with an object array [{obj1}, {obj2}]
}
更新

正如您所注意到的,编码器被迫在回调方法中实现代码。然后,依赖于来自第一个请求的数据的其他方法或请求往往会使代码的结构变得复杂

const processVideos = function(data) {
  if(!data) {
    // do something when data is empty
  }

  // process videos here
}

const notifyError = function(err) {
  if(!err)
     return

  // do something with the error here
}

Video.find(function(err, data) {
  processVideos(data)
  notifyError(err)
})

始终使用你的“天才”和编程模式来避免复杂的代码、大的方法和不可读的部分。

你知道缩短代码的方法吗?我有3个集合要查询并呈现到ejs模板。这将使代码变得如此丑陋和难以理解。使用结构化编程可以避免编写糟糕的代码。我会在答案中给你举个例子。