【问题标题】:How to save userId in mongoose hook?如何在猫鼬钩子中保存 userId?
【发布时间】:2018-09-15 03:21:10
【问题描述】:

给定模式,我如何将userId 保存到createdByupdatedBy

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

在写入之前,我不确定如何将 userIdreq.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);
    });
  });
};

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    以下只是保存userId的另一种方式。

    具有 createdBy、updatedBy、createdAt、updatedAt 字段的示例模型:

    import mongoose from 'mongoose';
    
    const SupplierSchema = new mongoose.Schema(
      {
        name: {
          type: String,
        },
        createdBy: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User',
        },
        updatedBy: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User',
        },
      },
     {
       timestamps: {
         createdAt: true,
         updatedAt: true,
       },
     },
    );
    
    export default mongoose.model('Supplier', SupplierSchema);
    

    请注意,在从版本 ^4.13.17 开始的 mongoose 中,您可以直接在模式中简单地指定时间戳 createdAt、updatedAt。 https://mongoosejs.com/docs/4.x/docs/guide.html#timestamps

    然后在供应商控制器中将 req.user._id 分配给 createdBy、updatedBy 字段:

    import mongoose from 'mongoose';
    import { Supplier } from '../models';
    
    exports.create = async (req, res) => {
      const supplierToCreate = new Supplier({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        createdBy: req.user._id,
        updatedBy: req.user._id,
      });
    
      return supplierToCreate
        .save()
        .then(() =>
          res.status(201).json({
            message: 'New supplier is created successfully.',
          }),
        )
        .catch(errSaving => res.status(500).json({ error: errSaving }));
    };
    

    【讨论】:

      【解决方案2】:

      您无法访问 mongoose 钩子内的 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;
        }
      });
      

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

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

      【讨论】:

        猜你喜欢
        • 2012-08-08
        • 2018-03-04
        • 1970-01-01
        • 2012-09-01
        • 2013-08-14
        • 2021-06-27
        • 2021-07-05
        • 2013-10-27
        • 1970-01-01
        相关资源
        最近更新 更多