I want to add a key with values or update the values if the key exists. So far i managed to do it with. At the moment I am doing this with 2 calls. I am getting the object and then i am altering it. It would like to be able to do this at once. My concern is that function is getting called twice in a short period of time and the second call would not get the updated object. My Problem is that i am Adding a key to the object that is created by another webserver. Is my approach dangerous? Will the second call wait for a completion of the update or do i have to block the db somehow?
How can I add a key on update that is part of an object? The Object with the data looks like this.
{
key: "20170606000000$BgMKClY@$BgYEA10F@",
value: {
"quantity" : "0.3",
"hourbooking_id" : "$BgECBlECDg@"
}
}
The schema is the following:
var Hours = new Schema({
_id: ObjectId,
hours: {}
});
My code looks like this:
this.findHoursById = function(_id, callback){
Hours.findOne({
_id: _id
}, function(err, chours){
if(err || chours === null){
callback({
success: false,
error: 'User not found'
})
}else{
callback({
success: true,
error: 'none',
hours: chours.hours
});
}
})
};
this.addHours = function(_id, hours, callback){
var insertHours = {};
this.findHoursById(_id, function(result){
if(result.success){
insertHours = result.hours
}
insertHours[hours.key] = hours.value;
var CHours = new Hours({
_id: _id
});
CHours.update({$set: {hours: insertHours}}, {upsert: true}, function(err, num, n){
if (err){
console.log(err);
callback({ success: false, error: 'update hours error' });
//throw err;
}else{
callback({ success: true, error: 'none' });
}
});
});
};
via Silve2611
No comments:
Post a Comment