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