我有一个模型 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 中为深度嵌套数组编写更新查询?
发布评论