Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

node.js - Mongoose - Efficient update on an indexed array of mongoose.Schema.Types.Mixed

i have the following simplified Scheme:

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

My document can look like:

{
     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}
     ]
}

The collection rests is indexed with:

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

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?

thanks for the helpers!

EDIT: 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);
    });

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) {
  // ...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...