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

270
Vistas
How to get all instances from database?

I am forced to make "simple" project. The teacher wants mongoDb and node js. I want to get all cars from my db, but find() doesn't work. My code Model:

const mongoose = require('mongoose');

const CarSchema = mongoose.Schema({
    mark:{
        type: String,
        required: true,},
    model:{
        type: String,
        required: true,},
    price:{
        type: Number,
        required: true,},
    available: {
        type: Boolean,
        required: true,},
    pic_1:{
        type:String,
        required:true,
    },
    pic_2:{
        type:String,
        required:true,
    }


})

const Car = mongoose.model('Car', CarSchema)
module.exports = Car

Route:

router.get('/getAll', (req, res) =>{
    const cr=Car.find({});
    console.log(cr);
    res.render('main', {user: req.user, cars:cr} );

});

Console.log shows everytthing but not list of the cars ;) More strictly: it shows structure of app and directors. How to fix it? And how to do it without =>{} - it's very illegible,long and my eyes bleeding. I just want to take all cars from db, assign them to the var and then render view with that cars.

There are a lot of questions, but no one answer solved my issue! Best Regards

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Car.find() is an asynchronous operation.

Solution 1: Using async/await

router.get('/getAll', async (req, res) =>{
    const cr = await Car.find({});
    console.log(cr);
    res.render('main', {user: req.user, cars:cr} );

});

Solution 2: Using callback function

router.get('/getAll', (req, res) =>{
    Car.find({}, (error, cars) => {
        console.log(cars);
        res.render('main', {user: req.user, cars: cars} );
    });
});

If you don't want to use the arrow functions then change as shown below

() => {}    >    function() {}

Changes to your code

router.get('/getAll', async function(req, res) {
    const cr = await Car.find({});
    console.log(cr);
    res.render('main', {user: req.user, cars:cr} );
});

Reference:

Async/await

Making asynchronous programming easier with async and await

Mongoose - Model.find()

Arrow functions

over 4 years ago · Santiago Trujillo Denunciar
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