unicloud12-update结合command的数组高级操作

151 阅读2分钟

更新

文档在 unicloud--云数据库--云函数通过传统方式操作数据库--更新文档

针对数组的操作符 通过command在字段中插入数据

'use strict';
const db=uniCloud.database();
const dbCmd = db.command;
exports.main = async (event, context) => {
	let res = await db.collection("users").where({
    _id:"63d8b35e819ce8248e864ddf"
  }).update({
    //通过command使用unshift方法在数组前面插入值
    like:dbCmd.unshift(["唱","演戏"])
  })
  return res;
};

image.png

push向后追加 -- 可以追加一个或多个

'use strict';
const db=uniCloud.database();
const dbCmd = db.command;
exports.main = async (event, context) => {
	let res = await db.collection("users").where({
    _id:"63d8b35e819ce8248e864ddf"
  }).update({
    //通过command使用push方法在数组向后追加值
    like:dbCmd.push(["打游戏"])
  })
  return res;
};

image.png

pop 删除数组中最后一个

'use strict';
const db=uniCloud.database();
const dbCmd = db.command;
exports.main = async (event, context) => {
	let res = await db.collection("users").where({
    _id:"63d8b35e819ce8248e864ddf"
  }).update({
    //通过command使用push方法在数组向后追加值
    like:dbCmd.pop()
  })
  return res;
};

最后一条打游戏被删掉了 image.png

删除数组中第一个值

'use strict';
const db=uniCloud.database();
const dbCmd = db.command;
exports.main = async (event, context) => {
	let res = await db.collection("users").where({
    _id:"63d8b35e819ce8248e864ddf"
  }).update({
    //通过command使用push方法在数组向后追加值
    like:dbCmd.shift()
  })
  return res;
};

数组中的第一条唱被删除了 image.png

inc

更新指令。用于指示字段自增某个值,这是个原子操作,使用这个操作指令而不是先读数据、再加、再写回的好处是:

  1. 原子性:多个用户同时写,对数据库来说都是将字段加一,不会有后来者覆写前者的情况
  2. 减少一次请求:不需先读再写

之后的 mul 指令同理。

在文章阅读数+1、收藏+1等很多场景会用到它。如给收藏的商品数量加一

如果是自减就用自增方法然后在数字前面写-

  count: {
    fav: dbCmd.inc(-1)
  }

给数据表加一个字段,使他每次自增3

'use strict';
const db=uniCloud.database();
const dbCmd = db.command;
exports.main = async (event, context) => {
	let res = await db.collection("users").where({
    _id:"63d8b35e819ce8248e864ddf"
  }).update({
    //原子自增3
    love:dbCmd.inc(3)
  })
  return res;
};

image.png

点一次增加3 image.png

还有自乘mul和自除 自除没有方法,用自乘+小数点的方法实现

一些网站的销量、关注等数据就是造假的

  count: {
    fav: dbCmd.mul(0.1)
  }