I was having some issues getting a query into a an array of type StockDocument. For context here are a few declarations.
The definition of my stock model/interface:
const ticker = new mongoose.Schema({
ticker: String,
Price: Number,
Amount: Number,
PastPrices: [{ time: Number, value: Number }]
});
export interface StockDocument extends mongoose.Document {
ticker: string,
Price: number,
Amount: number
PastPrice:[{time:number, value: number}]
}
export const stock = mongoose.model<StockDocument>("Stocks", ticker);
The query I am trying to run:
let ArrayStocks : StockDocument[];
stock.find().sort({ Amount: -1 }).exec(function (err, docs){
// console.log(docs);
console.log("Type of docs: " + typeof(docs));
ArrayStocks = docs;
console.log("Type of ArrayStocks: " + typeof(ArrayStocks));
console.log(ArrayStocks);
});
console.log("ArrayStocks outside of the loop: " + ArrayStocks);
}
Console output of the code above:
ArrayStocks outside of the loop undefined
Type of docs object
Type of ArrayStocks object
[
{
_id: 61e61c2fcb0c149b8231b4ad,
ticker: 'DOOB',
Price: 1,
Amount: 5,
PastPrices: [ [Object] ],
__v: 0
},
{
_id: 61e61c3acb0c149b8231b4b1,
ticker: 'GME',
Price: 2,
Amount: 4,
PastPrices: [ [Object] ],
__v: 0
},
{
_id: 61e61c34cb0c149b8231b4af,
ticker: 'BRUH',
Price: 3,
Amount: 3,
PastPrices: [ [Object] ],
__v: 0
}
]
As you can see, for some reason it can print the query but is undefined outside of it, and it is not an array of StockDocument like it is supposed to be.
I want to be able to call ArrayStocks[0].Amount, ArrayStocks[0].ticker, etc outside of that function. Im new to asynchronous programming but I'm guessing it has something to do with that, however, I don't know how to fix it.