im running nodejs version v8.5.0 using nvm.
I have a simple index function which returns all the users in my mongo db using mongoose.
User.find({}, (err, results) => {
if (err) {
return res.json(err);
}
return res.json(results);
});
I'm trying to convert the traditional call back approach to the new async and await.
user.controller.js
'use strict';
const User = require('../models/user.model');
class UserController {
constructor() {
}
async index(req, res) {
try {
let result = await User.find({});
return res(result);
} catch (e) {
return res.json(e);
}
}
show(req, res) {
}
update(req, res) {
}
store(req, res) {
}
destroy(req, res) {
}
}
module.exports = UserController;
user.route.js
'use strict';
let express = require('express');
let router = express.Router();
let controller = require('../controllers/user.controller');
controller = new controller();
router.get('/', controller.index);
router.get('/:id', controller.show);
router.post('/', controller.store);
router.put('/:id', controller.update);
router.delete('/:id', controller.destroy);
module.exports = router;
However when i run this, i get an empty object back.
The empty object is the error (calling res.json(javascript_error) will return an empty object).
Instead of
return res(result);
use
res.send(result)
Related
I'm building MERN stack CRUD with goolge login
I'm running my server on port:3001
and frontend on port:3000
getAll() {
return axios.get("http://localhost:3001/jobs")
}
try to fetch data with session loggedin
router.get("/", util.isLoggedin, (req, res) => {
Job.find()
// .populate("author")
.limit(20)
.sort({ jobId: -1 })
.then((jobs) => res.json(jobs))
.catch((err) => res.status(400).json("Error:" + err))
})
const util = {}
util.isLoggedin = function (req, res, next) {
console.log(req.isAuthenticated())
if (req.isAuthenticated()) {
next()
} else {
console.log(req.isAuthenticated())
res.redirect("/")
}
}
module.exports = util
I can retrieve the data only on the server side, not frontend.
what can be the solution?
source code:
https://github.com/jamespark89/mern-communitywebsite
it seems like you are not awaiting your promise..
async getAll() {
return await axios.get("http://localhost:3001/jobs")
}
replace
getAll() {
return axios.get("http://localhost:3001/jobs")
}
with
async getAll() {
return await axios.get("http://localhost:3001/jobs")
}
Try to make your get request as an async function I usualy do that:
router.get("/", util.isLoggedin, async (req, res) => {
try {
const res = await Job.find()
// .populate("author")
.limit(20)
.sort({ jobId: -1 })
res.status(400).json({ res })
} catch(err) {
res.status(400).json("Error:" + err)
}
})
const express = require('express')
const Task = require('../models/task-model')
const auth = require('../middleware/auth')
const router = new express.Router()
router.post('/tasks', auth, async (req, res) => {
const task = new Task({
...req.body,
owner: req.user._id
})
try {
await task.save()
res.status(201).send(task)
}
catch (error) {
res.status(400).send(error)
}
})
router.get('/tasks/count', auth, async (req, res) => {
try {
const count = await Task.countDocuments({})
if (!count) {
res.send(404).send()
}
res.send(count)
}
catch (error) {
res.status(500).send(error)
}
})
module.exports = router
Every route except count is working.
I have tried count() function, but it is deprecated.
Now I am using countDocuments({}) but it gives 500 response.
I have tried estimatedDocumentCount() but same response.
Just an elementary question.
The following code return tasks successfully:
const mongojs = require('mongojs');
const db = mongojs('localhost:27017/tasks', ['tasks']);
router.get('/tasks', function(req, res, next) {
db.tasks.find(function(err, tasks) {
if (err) {
res.send(err);
}
if (tasks) {
res.json(tasks);
}
});
});
But, when I split it and call it as callback, it returns: References: tasks is not defined.
Repository.js:
const mongojs = require('mongojs');
const db = mongojs('localhost:27017/tasks', ['tasks']);
module.exports = {
ReadAllTasks(callback) {
db.tasks.find(function(err, tasks) {
if (err) {
callback(err, null);
}
callback(null, tasks);
});
}
}
Route.js:
const express = require('express');
const router = express.Router();
const repository = require('./repository');
router.get('/tasks', function(req, res, next) {
repository.ReadAllTasks(function(err, tasks) {
if (err) {
res.send(err);
}
if (tasks) {
res.json(tasks);
}
})
});
module.exports = router;
Anyone know to fix it?
try this, because you are not returning the valid object.
module.exports = {
ReadAllTasks: (callback)=>{
db.tasks.find(function(err, tasks) {
if (err) {
callback(err, null);
}
callback(null, tasks);
});
}
}
I have this code:
exports.get_transducer_edit = (req, res) => {
if(req.isAuthenticated()){
Transducer.findById(req.params.id, (err, foundTransducer) => {
if(err){
res.redirect('/en/dashboard');
} else {
res.render('dashboard/transducer_edit-dashboard', {transducer: foundTransducer});
}
});
}else{
req.flash('error','You need to log in to do that');
res.redirect('/dashboard/login');
}
};
it runs with no problem, but then when I created a middleware in middleware/index.js:
var middlewareObj = {};
middlewareObj.isLoggedIn = function(req, res, next){
if(req.isAuthenticated() ) {
return next();
}
res.redirect('/dashboard/login');
};
module.exports = middlewareObj;
I called it inside this code:
const middleware = require('../middleware');
const Transducer = require('../models/productTransducers');
exports.get_transducer_edit = middleware.isLoggedIn, (req, res) => {
Transducer.findById(req.params.id, (err, foundTransducer) => {
if(err){
res.redirect('/en/dashboard');
} else {
res.render('dashboard/transducer_edit-dashboard', {transducer: foundTransducer});
}
});
};
What am I doing wrong? Please help...
Sorry, I just solved.
I called the middleware in my route:
router.get('/en/dashboard/products/transducers/:id/edit', middleware.isLoggedIn, transducer_controller.get_transducer_edit);
I was trying to call it in my controller like:
exports.get_transducer_edit = middleware.isLoggedIn, (req, res) => {
...
wrong!
Thanks again.
I'm trying to reuse my controllers which handle database operations. I'm bit struggling with structuring my application. Here's what I have:
server.js
var apiController = require('./controllers/api');
router.get('/cars', function (req, res) {
// get all cars from DB and render view
apiController.getCars().then(function (cars) {
res.render('index', {cars: cars});
});
});
router.get('/api/cars', function (req, res) {
// get all cars from DB and return JSON
apiController.getCars().then(function (cars) {
res.json(cars);
});
});
controllers/api.js
module.exports = {
getCars: function () {
db.collection('cars').find().toArray( function (err, cars) {
if (err) throw err;
return cars;
});
},
// tried also something like this but this doesn't really work
// for my use case because I don't want to attach any particular
// res to the function
getCars: function (req, res, next) {
db.collection('cars').find().toArray( function (err, cars) {
if (err) throw err;
res.json(cars);
});
},
};
Your current problem is that you expect promises as return in server.js while you use callbacks in the controller. I suggest you change your function getCars to return a Promise. Don't know what ODM/ORM you're using but it might look like something like this:
getCars: function () {
return db.collection('cars').find();
},
server.js
var apiController = require('./controllers/api');
router.get('/cars', function (req, res) {
apiController.get('cars').then(function (cars) {
res.render('index', {cars: cars});
});
});
router.get('/api/cars', function (req, res) {
apiController.get('cars').then(function (cars) {
res.json(cars);
});
});
controllers/api.js
var Promise = require('bluebird');
module.exports = {
get: function (modelName) {
return new Promise(function(resolve,reject){
return db.collection(modelName).find().toArray(function(err, models){
if (err) {
return reject(err);
}
else {
return resolve(models);
}
});
});
}
};
server.js
var apiController = require('./controllers/api');
router.get('/cars', apiController.getCars);
controllers/api.js
function getCarsAsync(req, res, next){
db.collection('cars').find().then(function(carsData){
if(carsData){
return res.send(carsData);
}
else{
return res.status(401).send('User is not authorized');
}
}).catch(function(err){
return next(err);
});
}
module.exports = {
getCars: getCarsAsync
};