【问题标题】:Mongoose pre('save') doesn't add created_atMongoose pre('save') 不添加 created_at
【发布时间】:2018-04-22 06:31:05
【问题描述】:

我有以下问题。当我想将新书发布到我的数据库时,我还想添加 created_at 变量。我只是快递 4 和猫鼬。实际上我的代码有效,但它没有添加 created_at (但添加了其他代码)。

发帖功能

import { Books } from './../schemas/book.schema';
class BookRouter {
    private postBook(req: Request, res: Response, next: NextFunction) {
        const book = {
            title: req.body.title,
            author: req.body.author
        };  
        Books.create(book, (err, book) => {
            if(err)
                return res.status(404).send(err);
            return res.status(200).send(book);
        });
    }
}

和我的架构类

import { NextFunction } from 'express';
import { Schema, model } from 'mongoose';
class BookSchema {
    private bookSchema: Schema;
    constructor() {
        this.setSchema();
    }
    public getBookSchema(): Schema {
        return this.bookSchema;
    }
    private setSchema() {
        this.bookSchema = new Schema({
            createdAt: Date,
            title: String,
            author: String
        }).pre('save', (next: NextFunction) => this.preSave(next));
    }

    private preSave(next: NextFunction) {
        if(!this.bookSchema.get('createdAt'))
            this.bookSchema.set('createdAt', new Date);
        next();
    }
}
const book = new BookSchema;
export const Books = model('Books', book.getBookSchema());

有什么想法吗?做了6个小时,还没有找到解决办法。

【问题讨论】:

  • 为什么不直接将timestamps: true 传递给您的架构?这样createdAtupdatedAt 就会自动生成。您也可以将其设置为名称为created_at,而不是默认的createdAt
  • 但是如果我想使用 bcrypt 并加密我的密码怎么办,这与 pre 方法相同:/
  • 你使用的是打字稿吗?
  • 是的。我发现如果我使用普通函数(下一个){ this.createdAt = new Date() };它正在工作,但使用箭头功能却不行。为什么?
  • 箭头函数没有自己的this。见此链接:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: express mongoose save schema


【解决方案1】:

您需要将中间件修改为:

private preSave(this: Document, next: NextFunction) {
    if(!this.bookSchema.get('createdAt'))
        this.bookSchema.set('createdAt', new Date);
    next();
}

将 Document 替换为您的文档定义。

HTH。

【讨论】:

    猜你喜欢
    • 2015-07-20
    • 2021-01-08
    • 2018-11-17
    • 1970-01-01
    • 2016-04-29
    • 2014-03-22
    • 2017-01-31
    • 1970-01-01
    • 2019-07-26
    相关资源
    最近更新 更多