【发布时间】:2022-11-23 05:42:13
【问题描述】:
我只想在插入之前检查控制器上的所有 req.query 就像我的 IGroupDocument 之后,才将文档添加到我的数据库集合中。
这方面的最佳做法是什么?
IGroup文档:
import { Document, Model } from "mongoose";
export interface IGroup {
firstName: string;
lastName: string;
age?: number;
email: string,
dateOfEntry?: Date;
}
export interface IGroupDocument extends IGroup, Document {}
控制器:
function create(req: Request, res: Response) {
// req.query validation: if firstName, lastName and email exist and type string, and then make a document from req.query call newGroup.
GroupModel.create(newGroup)
res.send(`${req.query.name} created`)
}
【问题讨论】:
-
您至少应该为我们提供一些代码示例,以了解您目前正在努力解决的问题。你使用的是带有 mongoose 库的普通 javascript 吗?您要在控制器级别还是模式级别进行验证?
-
对不起,我已经解决了这个问题。现在更清楚了
-
好吧,不。您甚至没有包含要将任何内容存储到数据库的代码。您也没有包含与
IGroupDocument相关的任何代码。您甚至根本没有包括应该检查的内容。是否应该检查某些查询参数是否为字符串、是否具有一定长度等? -
感谢您的关注!现在更清楚了吗?
标签: typescript mongoose crud