【问题标题】:I need to push into nested array in node mongoose我需要推入节点猫鼬中的嵌套数组
【发布时间】:2021-04-02 17:18:07
【问题描述】:

我使用节点猫鼬。 我需要更新这个数组推送新项目到Breackfast(mealList.foodList.breackfast || any), 我想按时间添加新的foodlist,请您给我建议如何做,

    {
        "_id": "5fe43eb44cd6820963c98c32",
        "name": "Monday Diet",
        "userID": "5f225d7458b48d0fe897662e",
        "day": "Monday",
        "type": "private",
        "mealList": [
            {
                "_id": "5fe43eb44cd6820963c98c33",
                "time": "Breakfast",
                "foodList": [
                    {
                        "_id": "5fe43eb44cd6820963c98c34",
                        "foodName": "Eggs",
                        "Qty": "2",
                        "calories": "calories",
                        "category": "category"
                    }
                    
                ]
            },
            {
                "_id": "5fe43eb44cd6820963c98c36",
                "time": "Lunch",
                "foodList": [
                    {
                        "_id": "5fe43eb44cd6820963c98c37",
                        "foodName": "food1",
                        "Qty": "100g"
                    },
                ]
            }
        ],
        "createdAt": "2020-12-24T07:09:40.141Z",
        "updatedAt": "2020-12-24T07:09:40.141Z",
        "__v": 0
    }

我试过了:

Diet.updateOne(
    { "Diet.mealList._id": req.body.mealId },
    // { $push: { "Diet.0.mealList.$.foodList": req.body.foodList } },
    { $push: { foodList: req.body.foodList } }
)

【问题讨论】:

标签: node.js mongoose mongoose-schema


【解决方案1】:

一些修复:

  • 使用mongoose.Types.ObjectId 将字符串_id 转换为对象类型
  • 从第一个删除Diet并将对象推入foodList
Diet.updateOne({
  "mealList._id": mongoose.Types.ObjectId(req.body.mealId)
},
{
  $push: {
    "mealList.$.foodList": req.body.foodList
  }
})

Playground

【讨论】:

    猜你喜欢
    • 2019-11-15
    • 2016-06-05
    • 2018-10-30
    • 1970-01-01
    • 2019-02-04
    • 2018-05-10
    • 2013-11-24
    • 2022-01-03
    • 2021-07-26
    相关资源
    最近更新 更多