使用mongoose有效地查询索引子数组

我试图在MongoDB中存储每个用户的卡片集合。 collections基本上是一系列拥有相关数量的自有卡。

Collection { user: ..., cards: [ {cardId: 133, qty: 3}, {cardId: 22, qty: 1} ] } 

我正在用node.js[ {cardId: 133, qty: 2}, {cardId: 111, qty: 4} ]构build一个API,以[ {cardId: 133, qty: 2}, {cardId: 111, qty: 4} ]的forms接收请求。

现在,我需要在cards数组中创build卡片条目(如果它不存在),或者在数量已经存在的情况下更新数量。

我需要这样做,因为集合可能包含数以千计的卡,所以我想出了这个Schema

 var OwnedCard = new Schema({ cardId: { type: String, index: true, required: true}, qty: { type: Number, required: true} }); var Collection = new Schema({ userId: { type: String, index: true }, cards: [OwnedCard] }); 

我不知道如何利用cardId上的index来快速定位和更新(或创build如果缺less)在子arrays中的卡

基本上,对于每个{ cardId: ..., qty: xxx }请求=>查找/更新,或者在cards数组中创build正确的条目。

到目前为止,我已经(find用户的集合):

 Collection.findOne({userId: userId}, function (err, collection) { var cards = collection.cards; // the cards }); 

但是我不想把它们作为一个Javascript对象进行过滤,因为它没有利用索引,而且可能很慢,而是寻找一种方法让mongo快速检索单个卡片条目。

任何想法如何实现这一目标?