如何在 mongodb 中为深度嵌套数组编写更新查询? [英] How to write update query in mongodb for deeply nested array?

查看:51
本文介绍了如何在 mongodb 中为深度嵌套数组编写更新查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型 Customer 及其架构

Hi I have a Model Customer and its schema

var customerSchema = new Schema({
    name: {type: String, required:true, trim: true, index: true, default: null, sparse: true},
    cardInfo: { type: [cardInfoSchema]}
})

var cardInfoSchema = new Schema({
    customerId : { type: String, required: true, index: true, unique: true,trim : true,  sparse: true},
    cards: { type:[cardsSchema], default:[]}
}, {_id: false});

var cardsSchema = new Schema({
    cardType   : { type: String, required: true, default: null, trim : true },
    isActive   : { type: String, required: true,  trim: true }, //0: not active, 1: active
    cardId     : { type: String, required: true,  trim: true },
    createdAt  : { type: Date, default: Date.now, required: true }
})

我想添加多张客户卡,所以我正在使用这个

I want to add multiple cards of customer so I am using this

var dataToSet = {
                    'cardInfo.customerId': '25934285649875',
                    $push: {
                        'cardInfo.cards': {
                            cardId: 'somecardid,
                            cardType: 'type',
                            createdAt: new Date().toISOString(),
                            isActive: true
                        }
                    }
                };

但我收到此错误.

不能使用部分(cardInfo.customerId的cardInfo)遍历元素({cardInfo: []})

cannot use the part (cardInfo of cardInfo.customerId) to traverse the element ({cardInfo: []})

请帮助我编写查询以使用 mongodb 或 mongoose 添加客户卡.

Please help me in writing the query to add card of customer using mongodb or mongoose.

推荐答案

尝试 positional $ 操作符在您的更新中用作匹配查询文档的第一个元素的占位符,并且在您使用它时确保cards 数组字段必须作为查询文档的一部分出现.在您的情况下,您希望将 card 文档添加到 'cards' 数组中,但前提是 cardId 不存在:

Try the positional $ operator in your update which acts as a placeholder for the first element that matches the query document, and when you use it make sure the cards array field must appear as part of the query document. In your case you'd want to add a card document into the 'cards' array, but only if the cardId doesn't exist:

var query = {        
    "cardInfo.cards.cardId": { "$nin": ["somecardid"] }
};
var update = {        
    "$push": {
        "cardInfo": { "customerId": "25934285649875" },
        "cardInfo.$.cards": {
            cardId: "somecardid",
            cardType: "type",
            createdAt: new Date().toISOString(),
            isActive: true
        }
    }
};

Customer.update(query, update, function (err, result) { ... }); 

这篇关于如何在 mongodb 中为深度嵌套数组编写更新查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆