更新文档

更新指定文档

collection.doc().update(Object data)
未使用set、remove更新操作符的情况下,此方法不会删除字段,仅将更新数据和已有数据合并。
参数说明

参数 类型 必填 说明
data object 更新字段的Object,{‘name’: ‘Ben’} _id 非必填

响应参数

参数 类型 说明
updated Number 更新成功条数,数据更新前后没变化时会返回0
  1. let res = await collection.doc('doc-id').update({
  2. name: "Hey",
  3. count: {
  4. fav: 1
  5. }
  6. });
  1. // 更新前
  2. {
  3. "_id": "doc-id",
  4. "name": "Hello",
  5. "count": {
  6. "fav": 0,
  7. "follow": 0
  8. }
  9. }
  10. // 更新后
  11. {
  12. "_id": "doc-id",
  13. "name": "Hey",
  14. "count": {
  15. "fav": 1,
  16. "follow": 0
  17. }
  18. }

更新数组时,已数组下标作为key即可,比如以下示例将数组arr内下标为1的值修改为 uniCloud

  1. let res = await collection.doc('doc-id').update({
  2. arr: {
  3. 1: "uniCloud"
  4. }
  5. })
  1. // 更新前
  2. {
  3. "_id": "doc-id",
  4. "arr": ["hello", "world"]
  5. }
  6. // 更新后
  7. {
  8. "_id": "doc-id",
  9. "arr": ["hello", "uniCloud"]
  10. }

更新文档,如果不存在则创建

collection.doc().set()
注意:
此方法会覆写已有字段,需注意与update表现不同,比如以下示例执行set之后follow字段会被删除

  1. let res = await collection.doc('doc-id').set({
  2. name: "Hey",
  3. count: {
  4. fav: 1
  5. }
  6. })
  1. // 更新前
  2. {
  3. "_id": "doc-id",
  4. "name": "Hello",
  5. "count": {
  6. "fav": 0,
  7. "follow": 0
  8. }
  9. }
  10. // 更新后
  11. {
  12. "_id": "doc-id",
  13. "name": "Hey",
  14. "count": {
  15. "fav": 1
  16. }
  17. }

批量更新文档

collection.update()

  1. const dbCmd = db.command
  2. let res = await collection.where({name: dbCmd.eq('hey')}).update({
  3. age: 18,
  4. })