SOLUTION #1
- Calling
find
on model Rent
will return a Promise.
- We need to
await
for the Promise to resolve or get rejected in case of some error.
- Always put
async\await
code inside a try-catch
block.
const express = require('express')
const Rent = require('../model/rent')
route = express()
route.use(express.json());
route.get('/rent', async (req, res) => {
try {
const rents = await Rent.find().exec();
res.send(JSON.stringify(rents));
} catch (error) {
res.send({error: error.message});
}
})
module.exports = route;
SOLUTION #2: If you want the result in JSON format. This how I would code.
* node_modules
* app.js
* db.js
* src
- routes
- api_router.js
File path\to\project\app.js
:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const db = require("./db");
var apiRouter = require('./src/routes/api_router');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', apiRouter);
module.exports = app;
File path\to\project\db.js
:
const mongoose = require('mongoose');
const DB_URI = "mongodb://localhost:27017/backend_app";
const DB_OPTIONS = {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
}
(async function () {
try {
await mongoose.connect(DB_URI, DB_OPTIONS);
console.log("MONGOOSE: Connected to the database!");
} catch (error) {
console.log("MONGOOSE ERROR");
console.log(error);
}
})();
File path\to\project\src\routes\api_router.js
:
const express = require('express');
const router = express.Router();
const Rent = require('../models/country_model')
router.get('/rent', async (req, res) => {
try {
const rents = await Rent.find().exec();
res.status(200).json({ data: rents }); // <- Check this line.
} catch (error) {
res.status(500).json({ error: error.message }); // <- Check this line.
}
})
module.exports = router;
Why find().exec()
?
find().exec()
on mongoose function will return an "real" Promise object. Read this.