通过填充

时间:2016-12-01 18:54:49

标签: node.js mongodb express mongoose

我有2个型号。

模型1:

const userSchema = new mongoose.Schema({
  email: { type: String, unique: true, required: true },
  password: { type: String, required: true },
  passwordResetToken: String,
  passwordResetExpires: Date,

  facebook: String,
  twitter: String,
  tokens: Array,

  profile: {
    name: String,
    gender: String,
    location: String,
    website: String,
    picture: String
  }
}, { timestamps: true });

模型2:

const reviveSchema = new mongoose.Schema({
  reviveShowName: {type: String, required: true},
  reviveTitle: {type: String, required: true},
  reviveCategory: {type: String, required: true},
  reviveGoal: {type: Number, required: true},
  revivePhoto: {type: String, required: true},
  reviveVideo: {type: String},
  reviveStory: {type: String},
  author: {
      id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
      }
    }
}, { timestamps: true });

如何将作者姓名传递给特定复兴的节目视图?

在我意识到我需要将作者的数据传递给视图之前,这就是我进入节目视图的方式:

exports.showRevive = (req, res, next) => {
  Revive.findById(req.params.id, (err, foundRevive) => {
    if(err) {
      console.log(err);
    } else {
      res.render('revive/show_revive', {revive: foundRevive});
    }
  });
};

虽然效果很好,但是为了在Revive show视图中获取作者的数据,我也尝试了这个:

exports.showRevive = (req, res, next) => {
  Revive.findById(req.params.id)
  .populate('author')
  .exec(function(err, foundRevive) {
    if(err) {
      console.log(err);
    } else {
      res.render('revive/show_revive', {revive: foundRevive});
    }
  });
};

那不起作用......你能指点我正确的方向吗?谢谢!

0 个答案:

没有答案