什么时候Mongoose的.pre(' init')会被调用?

时间:2018-04-11 07:12:59

标签: node.js mongoose mongoose-schema

我想制作游戏'每个都有自己独特的访问代码'。模式中的代码为FILE,每次创建新游戏时我都需要生成代码。

我认为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.

1 个答案:

答案 0 :(得分:2)

正如评论中所提到的,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: