I tried using Async-Await in NodeJs RESTful API but I seem to get an error I cannot resolve.
Here is my db.js
:
const User = require('../models/User'), user = {}; user.findUserByUsername = async function (username) => { try { const user = await User.findOne({username}); if (user) return {data: user, status: 200}; return {message: `Cannot find user with username: ${username}`, status: 404}; } catch (err) { return err; } }; module.exports = user;
And here is my api.js
:
const express = require('express'), router = express.Router(), user = require('../db/db'); router.get('/user', async (req, res, next) => { const user = await user.findUserByUsername(req.query.username); // ^ // Cannot access 'user' before initialization if (!user.status) return next(user); res.status(user.status); res.doc = user.status === 404 ? user.message : user.data; next(); }); module.exports = router;
When making a HTTP request, my server is crashing at that point. Where is my mistake?
Advertisement
Answer
You’re mixing your variable names up. You have user
as an import, but you also have user
as a variable you’re trying to assign to as a result of findUserByUsername
.
Use different variable names, and follow the capitalization convention for this sort of database lookup:
const express = require('express'), router = express.Router(), User = require('../db/db'); router.get('/user', async (req, res, next) => { const user = await User.findUserByUsername(req.query.username);