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
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: