我想创建每个游戏都有自己独特的访问"代码"的'游戏'。代码required
在架构中,每次创建新游戏时都需要生成代码。
我认为schema.pre('init')
将是生成此访问代码的好地方:
GameSchema.pre('init', function(next) {
// Code generation logic happens here
this.code = myNewlyGeneratedCode
next()
}
不幸的是,这将返回一条错误消息:ValidationError: Game validation failed: code: Path 'code' is required.
为什么这不起作用?在实例化新游戏之前,我是否必须只创建一个code
?
如注释中所述,pre('save')
是在文档存储在数据库中之前运行的中间件。 当从 Mongodb 查询返回文档时,pre('init')
会被调用。
演示文档中间件顺序的最简单方法是使用一个简单的示例:
49768723.js
#!/usr/bin/env node
'use strict';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Schema = mongoose.Schema;
var count = 0;
const schema = new Schema({
name: String
});
function log(str) {
console.log(`${++count}: ${str}`);
}
schema.pre('save', function () {
log('pre-save');
});
schema.pre('init', function () {
log('pre-init');
});
schema.post('save', function () {
log('post-save');
});
schema.post('init', function () {
log('post-init');
});
schema.pre('validate', function () {
log('pre-validate');
});
schema.post('validate', function () {
log('post-validate');
});
schema.pre('remove', function () {
log('pre-remove');
});
schema.post('remove', function () {
log('post-remove');
});
const Test = mongoose.model('test', schema);
const test = new Test({ name: 'Billy' });
async function main() {
await test.save();
log('saved');
await Test.findOne({ _id: test.id });
log('found');
await test.remove();
log('removed');
return mongoose.connection.close();
}
main();
输出
stack: ./49768723.js
1: pre-validate
2: post-validate
3: pre-save
4: post-save
5: saved
6: pre-init
7: post-init
8: found
9: pre-remove
10: post-remove
11: removed
stack: