Mongoose 的 .pre('init') 什么时候被调用? [英] When exactly does Mongoose's .pre('init') get called?

查看:74
本文介绍了Mongoose 的 .pre('init') 什么时候被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建游戏",每个游戏都有自己独特的访问代码".代码在架构中是必需的,每次创建新游戏时我都需要生成一个代码.

I want to create 'games' which each have their own unique access 'code'. The code is required in the schema, and I need to generate a code each time a new game is created.

我认为 schema.pre('init') 是生成此访问代码的好地方:

I thought schema.pre('init') would be a good place to generate this access code:

GameSchema.pre('init', function(next) {
    // Code generation logic happens here
    this.code = myNewlyGeneratedCode
    next()
}

不幸的是,这会返回一条错误消息:ValidationError:游戏验证失败:代码:需要路径代码".

Unfortunately, this returns an error message: ValidationError: Game validation failed: code: Path 'code' is required.

为什么这不起作用?在实例化一个新游戏之前,我是否只需要创建一个 code?

Why doesn't this work? Do I have to just create a code before I instantiate a new game?

推荐答案

正如评论中提到的,pre('save') 是在您的文档存储到数据库之前运行的中间件.pre('init') 在您的文档从 mongodb 查询返回时被调用.

As mentioned in the comments, pre('save') is the middleware that runs before your document gets stored in the db. pre('init') gets called on your documents when they are returned from mongodb queries.

演示文档中间件顺序的最简单方法是举一个简单的例子:

The easiest way to demonstrate the order of document middleware is with a simple example:

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:

这篇关于Mongoose 的 .pre('init') 什么时候被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆