// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init();
const db = cloud.database();
var user = null ;
// 云函数入口函数
exports.main = (event, context) => {
console.log("1")
console.log(event);
const wxContext = cloud.getWXContext();
try {
//先用openid去查询数据库里存不存在记录。不存在则插入,存在则更新。
db.collection('userInfo').where({
openid:wxContext.OPENID // 填入当前用户 openid
}).get().then(res => {
console.log(res.data)
console.log("2")
if(res.data){
console.log("3")
//更新
db.collection('userInfo').where({
openid:wxContext.OPENID
})
.update({
data: {
avatarUrl: event.updateData.avatarUrl,
city: event.updateData.city,
country: event.updateData.country,
gender: event.updateData.gender,
language: event.updateData.language,
nickName: event.updateData.nickName,
province: event.updateData.province,
},
})
}else{
console.log("4")
//插入
db.collection('userInfo').add({
// data 字段表示需新增的 JSON 数据
data: {
// _id: 'todo-identifiant-aleatoire', // 可选自定义 _id,在此处场景下用数据库自动分配的就可以了
openid: wxContext.OPENID,
appid: wxContext.APPID,
avatarUrl: event.updateData.avatarUrl,
city: event.updateData.city,
country: event.updateData.country,
gender: event.updateData.gender,
language: event.updateData.language,
nickName: event.updateData.nickName,
province: event.updateData.province,
createTime: new Date(),
isVip: false
}
})
}
})
console.log("5")
db.collection('userInfo').where({
openid:wxContext.OPENID // 填入当前用户 openid
}).get().then(res => {
console.log("6")
console.log(res.data[0])
user = res.data[0];
})
console.log("7")
return {
event,
openid:wxContext.OPENID,
appid:wxContext.APPID,
unionid:wxContext.UNIONID,
user
}
} catch (e) {
console.error(e)
}
}
本地调试日志如图