我有一个使用Mongoose库连接到MongoDB的node-express应用程序。 但是我在让自定义Mongoose插件在将文档保存到数据库之前对文档进行更改时遇到了问题。 这是我定义插件的方式:
const requestContext = require('request-context');
module.exports = (schema, options) => {
schema.pre('save', next => {
const author = requestContext.get('request').author;
this._createdBy = author.sub;
this._owner = author.sub;
this._groupOwner = author.group;
next();
});
schema.pre('findOneAndUpdate', next => {
const author = requestContext.get('request').author;
this._lastEditAt = Date.now();
this._lastEditBy = author.sub;
next();
});
}
然后将其添加到如下所示的模式中:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const trace = require('../plugins/trace');
const PostSchema = new Schema({
title: String,
Text: String,
category: String,
_createdAt: {
type: Date,
default: Date.now
},
_lastEditAt: Date,
_createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
_lastEditBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
_owner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},_groupOwner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Group'
}
});
PostSchema.plugin(trace);
exports.schema = PostSchema;
exports.model = mongoose.model('Post', PostSchema);
在我的Express控制器中:
const router = require('express').Router();
const Post = require('../model/post').model;
router.post('/', (req, res) => {
const post = new Post(req.body);
post.save()
.then(() => res.json(post))
.catch(err => res.status(400).json(err));
});
router.put('/', (req, res) => {
Post.findByIdAndUpdate(req.body._id, req.body, {new: true})
.then(post => res.json(post))
.catch(err => res.status(400).json(err));
});
由插件定义的预钩子被触发,但是它们带来的更改永远不会持久化到数据库中。这是Mongoose插件系统中的错误吗?
我已经尝试过使用Mongoose@4.13.9
和Mongoose@5.3.3
,但是没有用。
答案 0 :(得分:0)
整个周末我都在努力解决这个问题。
幸运的是,我找到了问题的根源。
首先:我在我的hook方法中使用了箭头函数,该函数改变了this
关键字的上下文。
因此,我必须使用旧的es5函数语法来定义我的钩子函数,如下所示:
const requestContext = require('request-context');
module.exports = (schema, options) => {
schema.pre('save', function(next) {
const author = requestContext.get('request').author;
this._createdBy = author.sub;
this._owner = author.sub;
this._groupOwner = author.group;
next();
});
}