Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

304
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda