[英]NodeJs Mongoose How can I get out a data from “find().then” in a “find().then”?
[英]mongoose .find() scope: How can I call found data out of the query?
我試圖在數組之外調用創建的變量,但它返回一個空數組。 有人可以解釋為什么 function 中的 console.log 可以工作,但不能在 function 之外工作。
// 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
}
應用程序.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 數組存儲在視頻變量中,以便可以調用全局變量?
當您執行此操作時:
Video.find(function(err, data) {
// something
console.log("one")
})
// nothing
console.log("two")
括號之間的 function 是find()
操作的回調。 這意味着它將在 find 執行結束時被回調,並且它可能會利用其 scope 內部的err
或data
參數。 它將執行console.log("one")
。
這種“等待”結果的方式是由於 js 的異步特性。
取而代之的是,回調方法外的代碼會在調用find 后立即觸發,不會等待 find 操作完成。 因此,在此示例中,將在one
之前打印two
。
在您的示例中,您嘗試在回調方法console.log(videos)
之外打印的變量videos
是空的,因為在videos
實際存在之前打印。
您應該在!err
情況下編寫所有回調代碼:
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)
})
始終使用您的“天才”和編程模式來避免復雜的代碼、大型方法和不可讀的部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.