Node.js 如何在mongoose钩子中保存用户ID?
给定您的模式,如何将Node.js 如何在mongoose钩子中保存用户ID?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,给定您的模式,如何将userId保存到createdBy和updatedBy 这似乎应该是一个简单的用例。我该怎么做 在编写之前,我不知道如何从req.user.id获取userId到模型 // graph.model.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ title: String, createdAt: Date, crea
userId
保存到createdBy
和updatedBy
这似乎应该是一个简单的用例。我该怎么做
在编写之前,我不知道如何从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
对象
我认为,您应该使用智能设置器来定义虚拟字段:
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
});
下面是另一种保存用户ID的方法 具有createdBy、UpdateBy、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。
然后在供应商控制器中,将req.user.\u id分配给创建的字段,由以下人员更新:
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 }));
};