更新指定文档
使用腾讯云时更新方法必须搭配doc、where方法使用,db.collection('test').update()
会报如下错误:
param should have required property 'query'
collection.doc().update(Object data)
未使用set、remove更新操作符的情况下,此方法不会删除字段,仅将更新数据和已有数据合并。
文档在unicloud--云函数通过传统方式操作数据库--获取集合的引用
update 更新
新建一个云函数cloudDemoUpdate
在页面中写一个按钮,通过按钮点击事件,点击按钮改变数据库中的值
这里就是一个回调函数,把云函数调用到这里来执行,这里调用,云函数就会自动执行
// 修改数据库内容
onUpdate(){
uniCloud.callFunction({
name:"cloudDemoUpdate"
}).then(res=>{
console.log(res);
})
}
云函数 这个小案例的逻辑是在前端通过点击事件连接云函数,在云函数中,通过ID超找到对应的数据,将数据的name字段和age字段的值进行更新
'use strict';
const db=uniCloud.database();
exports.main = async (event, context) => {
let res = await db.collection("users").doc("63d63c04819ce8248ecf8c8b").update({
name:"王五",
age:66
})
return res
};
云数据库中的值已经被更新了
有时候更新不成功,关闭uni的编辑器再打开就能成功了
一次性修改多条数据,不用doc
用where
没有的字段会新增,有的字段会修改
'use strict';
const db=uniCloud.database();
exports.main = async (event, context) => {
let res = await db.collection("users").where({
age:28
}).update({
tel:88888888888
})
return res;
};
ka这条数据有tel这个字段,小明没有tel字段,现在都有tel这个字段了
批量修改: 同时修改前两条数据的邮箱
'use strict';
const db=uniCloud.database();
const dbCmd = db.command;
exports.main = async (event, context) => {
let res = await db.collection("users").where({
_id:dbCmd.in(["63d63c04819ce8248ecf8c8b","63d63c1bf5cf3a4b66ecc42d"])
}).update({
mail:165416183@163.com
})
return res;
};
对数据库中的数组和对象类型的字符串进行更改
原始数据
'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({
// 修改like这个数组中 的第0项值为篮球
like:{
0:"篮球"
}
})
return res;
};
修改对象类型:
'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({
// 修改tabs这个对象中的jobs项值为歌手
tabs:{
jobs:"歌手"
}
})
return res;
};
改对象类型还能这么写:
'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({
// 修改tabs这个对象中的jobs项值为歌手
"tabs.jobs":"演员"
})
return res;
};