本文介绍了猫鼬-对mongoose.Schema.Types.Mixed的索引数组进行有效更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简化方案:

var restsSchema = new Schema({
    name: String
    menu: [mongoose.Schema.Types.Mixed]
});

我的文档如下所示:

{
     name: "Sandwiches & More",
     menu: [
                {id:1,name:"Tona Sandwich",price: 10, soldCounter:0},
                {id:2,name:"Salami Sandwich",price: 10, soldCounter:0},
                {id:3,name:"Cheese Sandwich",price: 10, soldCounter:0}
     ]
}

集合rests的索引是:

db.rests.createIndex( { "menu.id": 1} , { unique: true })

让我说我有这个ids [1,3]数组,因此我需要将ids = 1或3的menu项中的soldCounter递增1.

Lets say i have this array of ids [1,3] and based on that i need to increment the soldCounter by 1 of menu items with ids=1 or 3.

这样做的最有效方法是什么?

What will be the must efficient way of doing so?

感谢帮手!

我使用了以下解决方案:

I have used the following solution:

db.model('rests').update({ _id: restid,'menu.id': {$in: ids}}, {$inc: {'menu.$.soldCounter': 1}}, {multi: true},function(err) {
        if(err)
            console.log("Error while updating sold counters: " + err.message);
    });

其中,ids是带有菜单项ID的整数数组.restid是我们要在集合中编辑的特定文档的ID.

where ids is an array of integers with ids of menu items.restid is the id of the specific document we want to edit in the collection.

由于某些原因,仅更新ids数组中的第一个ID.

For some reason only the first id in the ids array is being updated.

推荐答案

有一种方法可以进行多次更新,这里是:只要确保您要更新的数组中有索引即可.

There is a way of doing multiple updates, here it is:Just make sure you have the indexes in the array you want to update.

var update = { $inc: {} };
for (var i = 0; i < indexes.length; ++i) {
  update.$inc[`menu.${indexes[i]}.soldCounter`] = 1;
}
Rests.update({ _id: restid }, update, function(error) {
  // ...
});

这篇关于猫鼬-对mongoose.Schema.Types.Mixed的索引数组进行有效更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:31