UniCloud云数据库增删改简单例子

195 阅读1分钟

捕获.JPG

.vue代码

template内代码

	<view class="gui-margin-top">
		<text class="gui-h5 gui-color-gray gui-bold">演示</text>
	</view>

	<view style="margin-top:38rpx;">
		<button type="default" class="gui-button gui-bg-black" formType="submit" style="border-radius:50rpx;"
			@click="getdateA">
			<text class="gui-color-white gui-button-text">点击 - 查看控制台</text>
		</button>
	</view>

	<!-- 数据库操作 -->
	<unicloud-db v-slot:default="{data, loading, error, options}" collection="Lxt-year">
		<view v-if="error">{{error.message}}</view>
		<view v-else>
			<view class="gui-margin-top">
				<text class="gui-h5 gui-color-gray gui-bold">返回整理后结果</text>
			</view></br>
			{{data[0].name}} </br>
			{{data[1].name}} </br>
			{{data[2].name}} </br>
			{{data[3].name}} </br>
			{{data[4].name}} </br>
			{{data[5].name}} </br>
			{{data[6].name}} </br>
			{{data[7].name}} </br>

		</view>
	</unicloud-db>
</view>

script内代码

  export default {
	data() {
		return {

		};
	},
	methods: {
		async getdateA() {
			const db = uniCloud.database();
			const collection = db.collection('Lxt-year');
			const dbCmd = db.command;

			//查询所有数据
			let res = await collection.get();

			//查询数据 - 单条
			// let res = await collection.where({
			// 	name: "2021年"
			// }).get()

			//查询数据 - 多条
			// let res = await collection.where({
			// 	name: dbCmd.in(["2021年", "2022年"])
			// }).get()

			//增加数据 -  单条
			// let res = await collection.add({
			// 	name: "2014年"
			// })

			//增加数据 -  多条
			// let res = await collection.add([
			// 	{name: "2013年",age:13},{name:"2012年",age:12}
			// ])

			//删除数据 判断成功失败
			// let res = await collection.where({_id:"62653782cec89c000156cccc"}).remove()
			// 	.then((res) => {
			// 		// console.log("删除成功,删除条数为: ",res.deleted);

			// 		uni.showToast({
			// 		  icon: 'none',
			// 		  title: '删除成功'
			// 		})
			// 	})
			// 	.catch((err) => {
			// 		console.log( err.message )
			// 	})
			// 	.finally(() => {

			// 	})



			//let res = await collection.get();
			//let aa = res.result.data[0].name;
			//return collection.where({name:aa}).update({

			//更新数据	
			// let res = await collection.where({_id:"625ac3374324b900014ec470"}).update({
			//   name: "2021年"
			// })
			// .then((res) => {
			// 			console.log("更新成功,更新条数为: ",res.result.updated);
			// 			uni.showToast({
			// 			 		  icon: 'none',
			// 					  title: '更新成功'
			// 					})
			// 	})
			// 	.catch((err) => {
			// 		console.log( err.message )
			// 		uni.showToast({
			// 		 		  icon: 'none',
			// 				  title: '更新失败'
			// 				})
			// 	})

			//控制台输出
			console.log(res)
		}
	}
}

数据库代码

{ "bsonType": "object", "required": [], "permission": { "read": true, "create": true, "update": true, "delete": true }, "properties": { "_id": { "description": "ID,系统自动生成" }, "name": { "bsonType": "string" } } }

##数据库内 字段及数据截图

捕获222.JPG