-1

This is my current codes written in express.js.

const router = express.Router();

router.post('/', async (req, res) => {
 const username = '';
  await User.findOne({_id: req.body.id,}, (err, user) => {
  if (err) // how to process this part?
  username = user.username;
  });
});

1 Answers1

-1

You can return user.username from .findOne() function. Note, a variable identifier declared using const cannot be reassigned, see Is it possible to delete a variable declared using const?.

const router = express.Router();

router.post('/', async (req, res) => {
  const username = await User.findOne({_id: req.body.id,}, (err, user) => {
    // return empty string or other value if `err`
    if (err) return "" // how to process this part?
    return user.username;
  });
});
guest271314
  • 1
  • 15
  • 104
  • 177