【问题标题】:Mongoose/MongoDB PUT: Push Object to Array if Object ID is unique within ArrayMongoose/MongoDB PUT:如果对象 ID 在数组中是唯一的,则将对象推送到数组
【发布时间】:2021-05-30 16:44:21
【问题描述】:

我想更新文档中的数组,前提是被推送到“items”数组的对象在“items”数组中具有唯一的 id。

{
    "_id": "6039e37cb6b60f4694a16705",
    "list_name": "Example Picklist",
    "author_id": "6027f627141a75567cc2e0b0",
    "author_name": "Test",
    "items": [
        {
            "upcs": [
                "111222333"
            ],
            "qty": 10,
            "id": "123456",
            "name": "Item A"
        },
        {
            "upcs": [
                "444555666"
            ],
            "qty": 22,
            "name": "Item B",
            "id": "987654"
        }
    ],
    "status": "initialized",
    "__v": 0
}

例如,我应该可以添加:

{ 
    "name": "Item C", 
    "qty": 99, 
    "upcs": ["111555999"], 
    "id": "111111" 
}

但不是:

{ 
    "name": "Item C", 
    "qty": 99, 
    "upcs": ["111555999"], 
    "id": "123456" 
}

在我尝试实现JohnnyHKthis 问题的回答之后,我的 put 请求目前没有拒绝具有现有 ID 的 req.bodys。

router.put('/:id', auth, async (req, res) => {
    const item = req.body; // insert above examples

    try {
        let picklist = await Picklist.findById(req.params.id);

        if (!picklist)
            return res.status(404).json({ json: 'Picklist not found' });

        picklist = await Picklist.findByIdAndUpdate(
            { _id: req.params.id, 'items.id': { $ne: item.id } },
            {
                $push: { items: item },
            },
            { new: true }
        );

        res.json(picklist);
    } catch (err) {
        console.error(err.message);
        res.status(500).json({ msg: 'Server Error' });
    }
});

我做错了什么?目前它会推送任何符合 Schema 的内容,并且不会阻止 ID 重复。

【问题讨论】:

  • 我认为我在这里可能有错误的是{ _id: req.params.id, 'items.id': { $ne: item.id } } 只是检查 item.id 是否不存在于 items 中,而不是在 items 数组的每个对象中。如果是这种情况,我如何告诉 mongoDB 我希望它在 items 数组中搜索每个未命名的对象以查找匹配的 ID?

标签: node.js mongodb mongoose put


【解决方案1】:

错误是我正在使用

Picklist.findByIdAndUpdate()

而不是

Picklist.findOneAndUpdate()

【讨论】:

    猜你喜欢
    • 2019-03-28
    • 2017-08-18
    • 2019-04-08
    • 1970-01-01
    • 2016-05-30
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多