【问题标题】:Mongodb, Delete one object from an array of objects using javascriptMongodb,使用javascript从一组对象中删除一个对象
【发布时间】:2021-10-15 21:06:28
【问题描述】:

我正在尝试从我的集合数组中删除一个对象,如下所示。这是MongoDB中的一个集合

在根据chartId删除特定对象之前,我需要检查userId和数组的名称。然后我需要删除对象。

我已经编写了这段代码,但它不起作用。有人会告诉我这段代码到底缺少什么。

           delChartObj.updateOne(
    { 'userId': userId },
    { $pull: { "Color": { "chartId": req_chart_id } } },
    { safe: true, multi: true}, function (err, obj) {
        if (err) { res.send.err }

        res.status(200).send({ msg: "Deleted Sucessfully" });
    });

在我的例子中,userId = ADAM, array = "Color" and chartID = time 我正在使用猫鼬来执行操作

delChartObj 是模型的对象

 const UserSchema = mongoose.Schema({
userId: { type: String, required: true, unique: true },
charts: { type: Object },


 });

【问题讨论】:

    标签: javascript arrays mongodb object mongoose


    【解决方案1】:

    在 pull 中试试这个

    { $pull: { "Chart.Color.$.chartId": req_chart_id } } },
    

    【讨论】:

    • 什么都没有发生,代码已执行,但尚未从集合中删除
    • 我已经更新了这个问题,基本上你没有提到顶级属性是图表
    【解决方案2】:

    你应该做 findOneAndUpdate,语法是这样的:

    Model.findOneAndUpdate(
    < condition>,
    { $pull: { "Color.$.chartId": req_chart_id } } }, // The actual Query
    { new: true }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多