【问题标题】:ObjectId mongodb equivalent for mongoose?ObjectId mongodb 等效于猫鼬?
【发布时间】:2022-01-18 05:59:15
【问题描述】:

所以,为了记录,这是有效的,但我们纯粹使用猫鼬,但我必须从 mongodb 导入 {ObjectId} 才能找到候选人的 ID。

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

我仍然不理解 mongoose 100%,所以也许我错过了一些东西,但如果不使用 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,请在这里问我,我会同时发布它们。 提前致谢。

【问题讨论】:

标签: node.js mongodb mongoose next.js


【解决方案1】:

Mongoose 在此处的 Schema.Types.ObjectId 也有一个 ObjectId:Mongooses ObjectId Type

Mongoose 还会读取字符串以匹配 objectid,因此您不必使用 new ObjectId("stringid")

mongoose 有一个用于获取 id 的 getter,您可以在其中获取 _id 作为字符串,而不是使用 _id 字段并获取 ObjectId。 这个“id”被称为虚拟字段,仅供参考。 您可以在此处阅读更多信息:document id getter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-06
    • 2020-07-25
    • 2016-11-21
    • 2016-01-01
    • 2016-11-06
    • 2017-10-08
    • 1970-01-01
    • 2020-04-15
    相关资源
    最近更新 更多