[英]expressjs with Typescript mongoose populating
Hello i am trying to Populate two documents in my Express project.您好,我正在尝试在我的 Express 项目中填充两个文档。 i am creating a Classroomschema , and it has an ref to the instructorschema.我正在创建一个 Classroomschema ,它有一个对教师模式的引用。
import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
import { IClassRoom } from '../interface/IClassRoom';
const ClassRoomSchema = new Schema({
instructor: {
ref: 'Instructor',
type: Schema.Types.ObjectId
},
classRoomName: {
type: String,
required: true
},
classRoomDescription: {
type: String,
required: true
},
creationDate: {
type: Date,
default: Date.now
},
classRoomGenre: {
type: String,
required: true
},
classRoomSkills: {
type: String,
required: true
},
classRoomVideo: {
type: String,
},
classRoomLevel: {
type: String
}
});
const ClassRoomModel = mongoose.model<IClassRoom>('Classroom', ClassRoomSchema);
export default ClassRoomModel;
i created an interface of every of my Schemas.我为我的每个架构创建了一个界面。 then i created an interface Request with the type of the interface Instructor然后我用接口 Instructor 的类型创建了一个接口请求
import { Request } from 'express';
import { Instructor } from './IInstructor';
export interface RequestWithInstructor extends Request {
instructor: Instructor;
}
i call the interface in my classRoom controller as i want to add a classroom with a controller , on the console i get the mistake UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_id' of undefined.我在 classRoom 控制器中调用接口,因为我想添加一个带有控制器的教室,在控制台上我收到错误 UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“_id”。 i want to know if someone can help me.我想知道是否有人可以帮助我。 this is the code这是代码
import { Request, Response } from 'express';
import ClassRoomModel from '../model/ClassRoomModel';
import InstructorModel from '../model/InstructorModel';
import { RequestWithInstructor } from '../interface/RequestC';
export class ClassRoomController {
public getAllClassRoom = async (req: Request, res: Response) => {
const classRoom = await ClassRoomModel.find()
res.json(classRoom);
}
public addClassRoom = async (req: RequestWithInstructor, res: Response) => {
const instructorid = req.instructor._id;
const classbody = req.body;
const instructor = await InstructorModel.findById(instructorid);
const newClassRoom = new ClassRoomModel({
...classbody,
classRoomVideo: req.file.path,
instructor: instructor
});
const savedClassRoom = await newClassRoom.save();
res.json(savedClassRoom);
}
The line that is currently throwing the error is:当前抛出错误的行是:
const instructorid = req.instructor._id;
This is because req
is not actually a RequestWithInstructor
, but a Request
provided to you by express.这是因为req
实际上不是RequestWithInstructor
,而是通过 express 提供给您的Request
。 You need to extract the body
from it before continuing with your logic.在继续您的逻辑之前,您需要从中提取body
。
Hence, the signature should be:因此,签名应该是:
public addClassRoom = async (req: Request, res: Response)
Assuming that addClassRoom
is a method called by a POST or PUT API call, you will need this line to happen before extracting the _id
field.假设addClassRoom
是一个由 POST 或 PUT API 调用调用的方法,您将需要在提取_id
字段之前执行此行。
const classbody = req.body;
Assuming that the body is expected to be a JSON object that conforms to the IClassRoom
interface, you could either cast the type and then validate, like假设主体应该是符合IClassRoom
接口的 JSON 对象,您可以转换类型然后进行验证,例如
const classRoom = req.body as IClassRoom;
or you could turn the interface into a class with a constructor (though that might not work well with Mongoose), and ideally add a validate method that you would then call from the controller, like:或者您可以将接口转换为带有构造函数的类(尽管这可能不适用于 Mongoose),并理想地添加一个验证方法,然后您将从控制器调用该方法,例如:
const classRoom = new ClassRoom(req.body);
if (!classRoom.validate()) {
throw new Error('Invalid ClassRoom object');
}
Then you can fetch the instructorId
like classRoom.instructor._id
if that's where it's expected to be in the JSON body.然后你就可以获取instructorId
像classRoom.instructor._id
如果这就是它的预期是在JSON体。
Your API controller function's job should be to take in JSON and validate it before it can do the Mongoose interaction.您的 API 控制器函数的工作应该是接收 JSON 并在它可以进行 Mongoose 交互之前对其进行验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.