gpt4 book ai didi

node.js - 如何在 mongoose hook 中保存 userId?

转载 作者:可可西里 更新时间:2023-11-01 09:59:04 25 4
gpt4 key购买 nike

给定你的架构,我如何将 userId 保存到 createdByupdatedBy

这看起来应该是一个简单的用例。我该怎么做?

在写入模型之前,我不确定如何从 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();
});

如果你有兴趣,这里是 Controller 代码:

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

最佳答案

下面只是另一种保存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 开始,您可以直接在模式中指定时间戳 createdAt、updatedAt。 https://mongoosejs.com/docs/4.x/docs/guide.html#timestamps

然后在供应商 Controller 中将 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 }));
};

关于node.js - 如何在 mongoose hook 中保存 userId?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30743565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com