【问题标题】:MongoDB push to array with predefined indexMongoDB推送到具有预定义索引的数组
【发布时间】:2019-02-28 11:12:21
【问题描述】:

如果我想将一个项目推送到数组的一个项目中,如何向 Mongoose 添加一个项目? 我想将其推送到具有预定义_id 的文档、具有预定义'id' 的'productList' 数组、'items' 数组。

{
"_id" : ObjectId("5ba94316a48a4c828788bcc9"),
"productList" : [
    {
        "id" : 1,
        "items" : [ 
            {
                "id" : 1,
                "name" : "FLOSS 500",
            }
        ]
    }
  ]
}

本以为应该是这样的,结果不行:

Products.findOneAndUpdate({_id: req.body._id, productList: {id: req.body.id}}, {$push: {'items': req.body.product}})

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您可以尝试使用位置运算符$。通过嵌套数组属性搜索使用点分隔语法:

    Products.findOneAndUpdate({ 
        _id: req.body._id, 
        'productList.id': req.body.id 
    }, { $push: { 'productList.$.items': req.body.product } });
    

    完整示例:

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    const Products = mongoose.model('Test', new Schema({
        productList: []
    }));
    
    mongoose.connect("mongodb://localhost:27017/myapp");
    
    let item = new Products({
        "_id": mongoose.Types.ObjectId("5ba94316a48a4c828788bcc9"),
        "productList": [
            {
                "id": 1,
                "items": [
                    {
                        "id": 1,
                        "name": "FLOSS 500",
                    }
                ]
            }
        ]
    });
    
    Products.deleteMany({}).then(() => {
        return Products.create(item);
    }).then(() => {
        return Products.findOneAndUpdate({
            _id: mongoose.Types.ObjectId("5ba94316a48a4c828788bcc9"),
            'productList.id': 1
        }, {
            $push: {
                'productList.$.items': {
                    "id": 2,
                    "name": "FLOSS 600",
                }
            }
        });
    }).then(() => {
        return Products.find({
            _id: mongoose.Types.ObjectId("5ba94316a48a4c828788bcc9"),
            'productList.id': 1
        });
    }).then(data => {
        console.log(data);
    
        if (data) {
            console.log(data[0].productList);
            /* [{"id":1,"items":[{"id":1,"name":"FLOSS 500"},{"id":2,"name":"FLOSS 600"}]}] */
        }
    }).catch(err => {
        console.error(err);
    });
    

    【讨论】:

    • 这没有成功。我可能认为我的查询方法是错误的。我是否理解正确,我可以通过 _id 找到文档并获得另一个字段,如“productList”作为回报,然后我将在哪里继续搜索其他嵌套文档?还是重构 Mongoose Schemas 并分离所有嵌套数组更好?
    • 按嵌套数组属性搜索使用点分隔语法'productList.id': req.body.id。我更新了我的答案。它对我有用。
    • 谢谢!这行得通,但我还必须为 Items 数组创建一个嵌套架构
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多