【问题标题】:MongoDB error trying to delete array item尝试删除数组项的 MongoDB 错误
【发布时间】:2022-03-30 02:33:15
【问题描述】:

我正在尝试从 MongoDB 模型中的数组中删除一个项目。 这是我的国家模型:

const CountrySchema = mongoose.Schema({
    name: { type: String, required: true },
    holidays: 
        [
            {
                day: {type: Number, required: true},
                month: {type: Number, required: true},
                description: { type: String, required: true }
            },
        ],
    states: { type: [String], required: true }
});

我已经有几个国家/地区的数据库,并且我有一个端点可以从该国家/地区删除假期。我从请求参数中获得了国家名称,并从 POST 中提供了假期信息。像这样:

{
    "day": 10,
    "month": 4,
    "description": "Random party"
}

所以我的函数 deleteHoliday 是这样的:

function deleteHoliday(req, res) {
    var country_name = req.params.country_name;
    var n_description = new Country(req.body.description);
    let query = Country.update({ 'name': country_name }, { '$pull': { holidays: { description: n_description }}})

    query.exec( (err, holidays) =>{
        //Check if no errors and send json back
        if(err){
            res.send(err);
        }
        res.status(200).json({message:"Holiday removed successfully"});
    })
}

我不太确定如何执行查询,但是在执行查询之前,我收到下一个错误:

ObjectParameterError: Document() 的参数“obj”必须是对象,随机方。

我只想删除带有给定描述的假日项目。在这种情况下随机方。

感谢您的帮助。

【问题讨论】:

    标签: arrays node.js json mongodb post


    【解决方案1】:

    对不起,我犯了一个错误,我传递的是对象类型 Country 而不是描述。

    var n_description = new Country(req.body.description);
    
    should be
    
    var n_description = req.body.description;
    

    已经解决了!

    【讨论】:

      【解决方案2】:

      错误就在这里,

      var n_description = new Country(req.body.description);
      

      需要一个简单的字符串,相应地更改它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-31
        • 2014-04-22
        • 2017-02-17
        • 2020-03-06
        • 1970-01-01
        • 1970-01-01
        • 2013-06-08
        • 1970-01-01
        相关资源
        最近更新 更多