如何在 mongodb 中为深度嵌套数组编写更新查询?

编程入门 行业动态 更新时间:2024-10-23 22:26:05
本文介绍了如何在 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 中为深度嵌套数组编写更新查询?

本文发布于:2023-11-22 18:30:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618527.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   数组   中为   深度   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!