如何将用户ID保存在猫鼬钩子中? [英] How to save userId in mongoose hook?

查看:50
本文介绍了如何将用户ID保存在猫鼬钩子中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given yon schema, how do I save userId to createdBy and updatedBy?

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

This seems like it should be an easy use case. How do I do it?

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

I'm not sure how to get userId from req.user.id to the model before being written.

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

如果您有兴趣,请在此处输入控制器代码:

Here's the controller code if you're interested:

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

推荐答案

您不能在猫鼬钩子内访问req对象.

You can't access req object inside of mongoose hook.

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

I think, you should define virtual field with a smart setter instead:

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字段:

Now all you have to do is to set modifiedBy field with correct userId value in your controller:

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

这篇关于如何将用户ID保存在猫鼬钩子中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆