Mongoose pre(' save')不会添加created_at

时间:2017-11-09 10:01:48

标签: express mongoose save schema

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

发布功能

amount

和我的架构类

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);
        });
    }
}

有什么想法吗?像6小时那样做,并没有找到解决方案。

1 个答案:

答案 0 :(得分:0)

您需要将中间件修改为:

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

用文档定义替换文档。

HTH。