【问题标题】:Mongoose: Accessing Data in User-ModelMongoose:在用户模型中访问数据
【发布时间】:2017-05-08 01:32:27
【问题描述】:

我正在尝试访问我的用户模型中的数据(使用 Express、Pug 和 Mongoose)。

这是我的架构:

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

这是我的 pug 模板文件:

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

我的路线如下所示:

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

我的错误在哪里?

浏览器显示Cannot read property 'name' of undefined 错误。

【问题讨论】:

  • User.find 返回一个承诺,渲染不会等待承诺解决。因此,您必须确保 render 仅在数据库的结果可用后才被执行。
  • 好的,谢谢。我自己找到了解决方案!

标签: node.js express mongoose pug


【解决方案1】:

我不得不使用回调函数!!!

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');
    }
  });
});

【讨论】:

  • 您甚至可以在if 条件之后将User.find 更深一层,因为users 数据显然只需要if (app.locals.userData.name)。避免不必要地访问数据库。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 2014-09-19
  • 1970-01-01
  • 2021-03-06
  • 2017-03-12
  • 2015-01-07
相关资源
最近更新 更多