递增和递减 RethinkDB 单值

Increment and decrement RethinkDB Single Value

RethinkDB单值自增自减

需要一些帮助,我正在学习 Nodejs 和 Rethinkdb。

目前我正在使用这个 RethinkDB 代码来执行更新操作。

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

现在的问题是:如何通过递增值来更新一行中的值?例如,假设它是关于汽车的库存。所以连续我会有:

    {
    "code":  "001" ,
    "brand":  "Ferrari" ,
    "stock":  "2"
    }

现在假设我制作了一个表格来控制库存中添加或删除的汽车数量。例如,假设我想添加 3 辆新法拉利。我如何更新价值 stock,将库存增加 3,总共 5,而不是用 2 代替 3。还可以说我卖了 2 辆 Ferraris,我怎样才能降低价值股票价值将为 0.

请原谅我糟糕的英语。不是我的母语。

如果我没理解错的话,这就是你可以做的。要添加,请使用如下内容:

r.table("items").get(id).update({
    stock: r.row("stock").add(2)
}).run(self.connection, callback);

要减去:

r.table("items").get(id).update({
    stock: r.row("stock").sub(3)
}).run(self.connection, callback);

更新

因此,数据库中的值实际上是字符串。你需要先强迫他们。这应该有效:

r.table("items").get(id).update({
    stock: r.row("stock").coerceTo("number").add(2).coerceTo("string")
}).run(self.connection, callback);