Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

295
Views
Getting a sorted database into an array in TypeScript using MongoDB(mongoose)

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
  }
]

Type that VS code says my doc is

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!