如何保存userId在mongoose钩?

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

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

我不知道如何从req.user.id到模型的userId

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

您不能访问mongoose钩内的req对象。

我想,你应该用一个聪明的setter来定义虚拟场:

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

现在你所要做的就是在控制器中设置正确的userId值的modifiedBy字段:

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