ObjectId mongodb等价于猫鼬



因此,记录在案,这是有效的,但我们纯粹使用mongoose,但我必须从mongodb导入{ObjectId}才能找到候选者的ID。

总结:我们正在创建候选人(候选人集合(,并为每个候选人插入一些面试。每个面试都有自己的_id(每个面试也被插入到面试集合中(,并且每个条目都有对应的Candidate _id。当我们想要删除该候选人时,我们需要删除所有具有其id的面试。

我仍然不能100%理解mongoose,所以也许我错过了一些东西,但如果不使用mongodb{ObjectId},我似乎无法使其工作

import Candidate from "../../../../models/candidateModel";
import Interview from "../../../../models/interviewModel";
import db from "../../../../utils/db";
import { NextApiRequest, NextApiResponse } from "next";
import { isAuth } from "../../../../utils/auth";
import { ObjectId } from "mongodb";
const handler = nc();
handler.use(isAuth);
handler.delete(async (req: NextApiRequest, res: NextApiResponse) => {
await db.connect();
const candidate = await Candidate.findById(req.query.id);
const candidateId = candidate._id.toString();
if (candidate) {
await candidate.remove();
await Interview.deleteMany({
candidate: new ObjectId(candidateId),
});
await db.disconnect();
res.send({ message: "Perfil de Candidato apagado" });
} else {
await db.disconnect();
res
.status(404)
.send({ message: "Não foi possivel encontrar o Perfil de Candidato" });
}
});

考虑到这个应用程序正在使用react/next/typescript/mongoose/axios,请给我答案。

await Interview.deleteMany({
candidate: new ObjectId(candidateId),
});

这是我想知道的部分。如果有人需要查看Schemas,请在这里询问我,我会同时发布它们。提前谢谢。

Mongoose在Schema.Types.ObjectId中也有一个ObjectId:Mongoose ObjectId Type

Mongoose还读取字符串以匹配对象,因此您不必使用新的ObjectId("stringid"(

mongoose有一个getter for id,您可以将_id作为字符串获取,而不是使用_id字段并获取ObjectId。这个";id";称为虚拟字段jsut-fyi。您可以在这里阅读更多信息:文档id getter

最新更新