Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

298
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda