Timo
Timo

Reputation: 261

Mongoose: Accessing Data in User-Model

I am trying to access the data in my User-Model (using Express, Pug and Mongoose).

This is my schema:

var userSchema = mongoose.Schema({
  userData: {
    name: { type: String, required: true, unique: true },
    password: String
  },
  notes: [ String ],
  contacts: [{
    name: String,
    notes: [ String ]
  }],
  locations: [ String ]
});

This is my pug-template file:

each user in allUsers
  p #{user.userData.name}

My Route looks like this:

app.get('/', function(req, res) {
  if (app.locals.userData.name) {
    res.render('app', {
      currentUser: app.locals.userData,
      allUsers: User.find({})
    });
  } else {
    res.redirect('signup');
  }
});

Where could be my mistake?

The Browser shows a Cannot read property 'name' of undefined error.

Upvotes: 0

Views: 173

Answers (1)

Timo
Timo

Reputation: 261

I had to use the callback function!!!

app.get('/', function(req, res) {
  User.find({}, function(err, users) {
    if (app.locals.userData.name) {
      res.render('app', {
        currentUser: app.locals.userData,
        allUsers: users
      });
    } else {
      res.redirect('signup');
    }
  });
});

Upvotes: 1

Related Questions