转换为ObjectId失败,导致模型错误的路径值 [英] Cast to ObjectId failed for value at path for model error

查看:135
本文介绍了转换为ObjectId失败,导致模型错误的路径值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的个人资料架构:

const mongoose = require('mongoose');

const ProfileSchema = new mongoose.Schema({
    user: {
        // Special field type because
        // it will be associated to different user
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user',
    },
    company: {
        type: String,
    },
    website: {
        type: String,
    },
    location: {
        type: String,
    },
    status: {
        type: String,
        required: true,
    },
    skills: {
        type: [String],
        required: true,
    },
    bio: {
        type: String,
    },
    githubusername: {
        type: String,
    },
    experience: [
        {
            title: {
                type: String,
                required: true,
            },
            company: {
                type: String,
                required: true,
            },
            location: {
                type: String,
            },
            from: {
                type: Date,
                required: true,
            },
            to: {
                type: Date,
            },
            current: {
                type: Boolean,
                default: false,
            },
            description: {
                type: String,
            },
        },
    ],
    education: [
        {
            school: {
                type: String,
                required: true,
            },
            degree: {
                type: String,
                required: true,
            },
            fieldofstudy: {
                type: String,
                required: true,
            },
            from: {
                type: Date,
                required: true,
            },
            to: {
                type: Date,
            },
            current: {
                type: Boolean,
                default: false,
            },
            description: {
                type: String,
            },
        },
    ],
    social: {
        youtube: {
            type: String,
        },
        twitter: {
            type: String,
        },
        facebook: {
            type: String,
        },
        linkedin: {
            type: String,
        },
        instagram: {
            type: String,
        },
    },
    date: {
        type: Date,
        default: Date.now,
    },
});

module.exports = Profile = mongoose.model('profile', ProfileSchema);

   

这是我的视图API.它不起作用.对于模型profile

This is my view api. It doesn't work. it only return Cast to ObjectId failed for value { 'experience._id': '5edcb6933c0bb75b3c90a263' } at path _id for model profile

router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
    try {
        const exp = await Profile.findById({
            'experience._id': req.params.viewexp_id,
        });

        if (!exp) {
            return res.status(404).json({ msg: 'Experience not found' });
        }

        res.json(exp);
    } catch (err) {
        console.error(err.message);
        res.status(500).send(err.message);
    }
});

我该如何解决?我尝试查看相同错误的stackoverflow.仍然似乎不起作用.

How can I fix this? I tried looking at the stackoverflow of the same errors. still it doesn't seem to work.

这就是我要打的

推荐答案

问题是您必须使用此函数mongoose.Types.ObjectId将字符串_id转换为mongoose object id,而我的建议是使用findOne函数代替findById

The problem is that you have to convert your string _id to mongoose object id using this function mongoose.Types.ObjectId and my suggestion is to use findOne function instead of findById,

var mongoose = require('mongoose');

router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
    
    try {

        let id = mongoose.Types.ObjectId(req.params.viewexp_id);
        
        const exp = await Profile.findOne(
            { "experience._id": req.params.viewexp_id }, 
            // This will show your sub record only and exclude parent _id
            { "experience.$": 1, "_id": 0 }
        );

        if (!exp) {
            return res.status(404).json({ msg: 'Experience not found' });
        }

        res.json(exp);

    } catch (err) {
        console.error(err.message);
        res.status(500).send(err.message);
    }

});

这篇关于转换为ObjectId失败,导致模型错误的路径值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆