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

269
Views
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 answers
Answer question

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 Report
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!