更新文档
更新指定文档
collection.doc().update(Object data)
未使用set、remove更新操作符的情况下,此方法不会删除字段,仅将更新数据和已有数据合并。
参数说明
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
data | object | 是 | 更新字段的Object,{‘name’: ‘Ben’} _id 非必填 |
响应参数
参数 | 类型 | 说明 |
---|---|---|
updated | Number | 更新成功条数,数据更新前后没变化时会返回0 |
let res = await collection.doc('doc-id').update({
name: "Hey",
count: {
fav: 1
}
});
// 更新前
{
"_id": "doc-id",
"name": "Hello",
"count": {
"fav": 0,
"follow": 0
}
}
// 更新后
{
"_id": "doc-id",
"name": "Hey",
"count": {
"fav": 1,
"follow": 0
}
}
更新数组时,已数组下标作为key即可,比如以下示例将数组arr内下标为1的值修改为 uniCloud
let res = await collection.doc('doc-id').update({
arr: {
1: "uniCloud"
}
})
// 更新前
{
"_id": "doc-id",
"arr": ["hello", "world"]
}
// 更新后
{
"_id": "doc-id",
"arr": ["hello", "uniCloud"]
}
更新文档,如果不存在则创建
collection.doc().set()
注意:
此方法会覆写已有字段,需注意与update表现不同,比如以下示例执行set之后follow字段会被删除
let res = await collection.doc('doc-id').set({
name: "Hey",
count: {
fav: 1
}
})
// 更新前
{
"_id": "doc-id",
"name": "Hello",
"count": {
"fav": 0,
"follow": 0
}
}
// 更新后
{
"_id": "doc-id",
"name": "Hey",
"count": {
"fav": 1
}
}
批量更新文档
collection.update()
const dbCmd = db.command
let res = await collection.where({name: dbCmd.eq('hey')}).update({
age: 18,
})