【问题标题】:MongoDb: Getting error while pushing documents in an arrayMongoDb:在数组中推送文档时出错
【发布时间】:2021-09-16 00:47:14
【问题描述】:

我需要后端方面的帮助。我正在使用邮递员,这是我的后端模型:

name: {
        type: String,
        required: [true, 'Department Name is Required']
    },
    description: {
        type: String,
        required: [true, 'Description is Required']
    },
agents: [
        {
            agentId: {
                type: String,
                required: [true, 'Agent ID is Required']
            },
            createdOn: {
                type: String,
                default: new Date()
            }
        }
]

我正在尝试将文档推送到代理数组中,但我遇到了一些错误。

路由和控制器如下:

Routes:
router.post('/enroll', (req, res) => {
    UserController.enroll(req.body).then(result => res.send(result))
});
Controllers:
module.exports.enroll = (params) => {
    return Department.findById({departmentId: params.departmentId}).then(department => {
        department.agents.push({userId: params.userId})

        return department.save().then((department, error) => {
            return (err) ? false : true
        })
    })
}

这是我得到的错误: (node:9916) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ departmentId: '60e27549c36af1272812c4e3' }" (type Object) at path "_id" for model "Department"

目标是查找部门id,会推送我已经获取的agent id。

【问题讨论】:

    标签: node.js mongodb mongodb-query


    【解决方案1】:

    试试

    改变

    return Department.findById({departmentId: params.departmentId}).

    return Department.findById(params.departmentId)


    findById 只接受 id 而不是对象

    【讨论】:

    • 谢谢。你能告诉我如何在邮递员中发布它吗?我的意思是,我如何在那里测试它?我正在使用的是:{“userId”:“60e17238415fab21f8cc6b28”,“departmentId”:“60e27549c36af1272812c4e3”}
    • @MarkWillowAldave 请分享您的路线详情?还要检查 - stackoverflow.com/questions/17007997
    • 不确定这是否正确:router.post('/enroll', (req, res) => { UserController.enroll(req.body).then(result => res.send(result)) });
    • Tushar 你能帮我解决这个问题吗 :-) stackoverflow.com/questions/68254282/…
    【解决方案2】:

    感谢图沙尔! 你很有帮助。

    我能够使用您提供的链接找到答案,并意识到我在代码本身上犯了一些错误。哈哈哈

    I've modified routes to:
    router.post('/enroll/:id', (req, res) => {
        const params = {
            departmentId: req.params.id,
           agentId: req.body.agentId
        }
        
        UserController.enroll(params).then(department => res.send(department))
    });
    
    Then, some of the lines in my controllers too:
    module.exports.enroll = (params) => {
        return Department.findById(params.departmentId).then(department => {
            department.agents.push({agentId: params.agentId})
    
            return department.save().then((department, error) => {
                return (error) ? false : true
            })
        })
    }
    

    它现在可以工作了。

    【讨论】:

    • 很高兴它帮助了你:)
    猜你喜欢
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 2018-12-11
    • 2016-10-12
    • 1970-01-01
    • 2016-04-17
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多