怎么修改数据库的数组中对象的元素值?
发布于 5 年前 作者 minxiang 5259 次浏览 来自 官方Issues
"_id": "用户123",
"_group1":
	0:{"tip": "审", "url": "cloud://abc123.png"}
	1:{"tip": "审", "url": "cloud://qwe321.png"}
"_group2":
	0:{"tip": "审", "url": "cloud://asd456.png"}
	1:{"tip": "审", "url": "cloud://dsa789.png"}

"_id": "用户456",
"_group1":
	0:{"tip": "审", "url": "cloud://bcd123.png"}
	1:{"tip": "审", "url": "cloud://zxc321.png"}
"_group2":
	0:{"tip": "审", "url": "cloud://bnm987.png"}
	1:{"tip": "审", "url": "cloud://tre789.png"}

如数据库中数据,我已知url的数组

"url":["cloud://abc123.png","cloud://dsa789.png","cloud://bnm987.png"]

将url数据中对应的tip值修改成"tip":"许"

该怎么写云函数呢?

1 回复
// 小程序端
wx.cloud.init()
wx.cloud.callFunction({
  name:'云函数名',
  data:{
    tip:'许',
    urls:["cloud://abc123.png","cloud://dsa789.png","cloud://bnm987.png"]
  }
}).then(res=>console.log(res))
.catch(res=>console.error(res))
// ================================================================
// 云函数
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database({
  env: '环境ID'
})
const _ = db.command

// 云函数入口函数
exports.main = async(event, context) => {
  var p1 = db.collection('xxxxx').where({
      '_group1.url':_.in(event.urls)
    }).update({
      data: {
        '_group1.$.tip':event.tip
      }
    }),
    p2 = db.collection('xxxxx').where({
     '_group2.url':_.in(event.urls)
    })
    .update({
      data: {
        '_group2.$.tip':event.tip
      }
    })
  return Promise.all([p1,p2])
}
回到顶部