unicloud云函数操作数据库

创建数据库

db_init.json

{
	"temperature": {
		"data": []
	}
}

添加记录

'use strict';
exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ' + event)
  const mydb = uniCloud.database();
  const userCollection = mydb.collection('temperature');
  let temperature=event.temperature;
  
  const currentTime=new Date();
  
  //const currentTime = new Date().toISOString();
  let month=currentTime.getMonth()+1;
  let riqi=currentTime.getFullYear() + '-' + month + '-' + currentTime.getDate();
  let hours=currentTime.getHours()+8;
  let minutes=currentTime.getMinutes();
  let seconds=currentTime.getSeconds();
  let currentTimeStr = riqi+" "+hours+":"+minutes+":"+seconds;
  
  let AM_PM = "" +((hours >= 12) ? "PM " : "AM " );
  
  let checkRecorded = await userCollection.where({
  	riqi: riqi,
	ampm:AM_PM
  }).get();
  const recordInfo = {
	  riqi:riqi,
	  ampm:AM_PM,
	  time:currentTimeStr,
	  temperature:temperature
  };
  if (checkRecorded.data && checkRecorded.data.length > 0) {
  	return {
  		code: -1,
  		errCode: 'Recorded',
  		msg: '今天已经记录'
  	}
  }else{
	  let updateResult = await userCollection.add(recordInfo);
	  return {
	  	code: 0,
	  	msg: '记录添加成功'
	  }
  }
};

获取数据列表

'use strict';
exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ' + event)
  const mydb = uniCloud.database();
  const userCollection = mydb.collection('temperature');
  
  let res = await userCollection.orderBy("riqi", "desc").get();
  
  console.log(res);
  //返回数据给客户端
  return res;
};

按照id查询

'use strict';
exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ' + event)
  const mydb = uniCloud.database();
  const userCollection = mydb.collection('temperature');
  let id=event._id;
  
  let res = await userCollection.where({"_id":id}).get();
  
  console.log(res);
  //返回数据给客户端
  return res;
};

删除数据

'use strict';
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ' + event)
	const mydb = uniCloud.database();
	const userCollection = mydb.collection('temperature');
	let id = event._id;
	console.log("-------"+id)
	let res = await userCollection.where({"_id": id}).remove();
	//返回数据给客户端
	return {
		code: 0,
		msg: '记录删除成功'
	};
};
百度大模型

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

腾讯云图