如何在mongoose hook中保存userId?

时间:2015-06-09 21:59:10

标签: node.js mongodb mongoose

鉴于yon架构,如何将userId保存到createdByupdatedBy

这似乎应该是一个简单的用例。我该怎么做?

我不确定在写作之前如何从userId获取req.user.id到该模型。

// graph.model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var schema = new Schema({
  title: String,

  createdAt: Date,
  createdBy: String,
  updatedAt: Date,
  updatedBy: String,
});

// This could be anything
schema.pre('save', function (next) {
-  if (!this.createdAt) {
    this.createdAt = this.updatedAt = new Date;
    this.createdBy = this.updatedBy = userId;
  } else if (this.isModified()) {
    this.updatedAt = new Date;
    this.updatedBy = userId;
  }
  next();
});

如果你有兴趣,这是控制器代码:

var Graph = require('./graph.model');

// Creates a new Graph in the DB.
exports.create = function(req, res) {
  Graph.create(req.body, function(err, thing) {
    if(err) { return handleError(res, err); }
    return res.status(201).json(thing);
  });
};

// Updates an existing thing in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  Graph.findById(req.params.id, function (err, thing) {
    if (err) { return handleError(res, err); }
    if(!thing) { return res.send(404); }
    var updated = _.merge(thing, req.body);
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(thing);
    });
  });
};

1 个答案:

答案 0 :(得分:3)

您无法访问mongoose hook中的req对象。

我认为,您应该使用智能设置器来定义虚拟字段:

schema.virtual('modifiedBy').set(function (userId) {
  if (this.isNew()) {
    this.createdAt = this.updatedAt = new Date;
    this.createdBy = this.updatedBy = userId;
  } else {
    this.updatedAt = new Date;
    this.updatedBy = userId;
  }
});

现在,您所要做的就是在控制器中设置modifiedBy字段,其中包含正确的userId值:

var updated = _.merge(thing, req.body, {
  modifiedBy: req.user.id
});