Reputation: 62
RethinkDB Increment and Decrement Single Value
Need some help, I'm learning Nodejs and Rethinkdb.
Currently I'm using this RethinkDB code to perform the Update operation.
r.table('items').get(id).update(item).run(self.connection, function(err, result) {
if(result && result.replaced === 1) {
res.send(item);
}
else if(err) {
debug("[ERROR] updateItem %s:%s\n%s", err.name, err.msg, err.message);
res.send({error: 'An error occurred when updating the item with id: ' + id});
}
else {
debug("[ERROR] updateItem (%s): %j", id, result);
res.send({error: 'An error occurred when updating the item with id: ' + id});
}
});
Now the question is: How can i update a value in a row by Incrementing its value? For example lets say its about the stock of a car. so in a row i'll have:
{
"code": "001" ,
"brand": "Ferrari" ,
"stock": "2"
}
Now lets say I make a form to control how many cars will be added or removed from the stock. So for example let's say I want to add 3 new Ferraris. How can i update the value stock, incrementing the stock by 3 for a total of 5 and not replacing 2 for 3. Also lets say I sold 2 Ferraris, how can I decrease the value so the stock value will be 0.
And please excuse my poor English. Not my native language.
Upvotes: 0
Views: 714
Reputation: 2488
If I understood correctly, here's what you can do. To add, use something like this:
r.table("items").get(id).update({
stock: r.row("stock").add(2)
}).run(self.connection, callback);
To substract:
r.table("items").get(id).update({
stock: r.row("stock").sub(3)
}).run(self.connection, callback);
Update
So, the values in the database are actually strings. You need to coerce them first. This should work:
r.table("items").get(id).update({
stock: r.row("stock").coerceTo("number").add(2).coerceTo("string")
}).run(self.connection, callback);
Upvotes: 2