I
I
IvanRobot2018-01-28 20:55:35
MongoDB
IvanRobot, 2018-01-28 20:55:35

How to configure express middleware to send queries to mongodb database?

Created a simple middleware to search for a user group in mongodb. But the server gives a 500 error without even starting to search.. What am I doing wrong?

// Dependencies
const express = require('express');
const mongoose = require('mongoose');
const router  = express.Router();

const Group = mongoose.model('Group');

// ------------------------------------------------------------------
// Middleware

let get_group = function (req, res, next) {
  console.log('middleware start');
  Group.findById(req.user.group, function(err, group) {
    console.log('search ready!');
    
    if (group.name == 'member') req.group = 'member';
    if (group.name == 'admin') req.group = 'admin';

    next();
  });
};

// ------------------------------------------------------------------
// Blocks

router.post('/', get_group, function(req, res) {
  console.log('root');
  if (req.group == 'member') {
    return res.render('blocks/collections');
  }

  return res.render('blocks/intro');
});

The logger throws an error:
middleware start
POST / 500 3.624 ms - 2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Tsvetkov, 2018-01-28
@yellow79

I think you forgot to describe the contents of the mongoose model in the 6th line,
let it be at least like this
const Group = mongoose.model('Group', {name:String});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question