微信小程序连接云数据库基本使用

这篇具有很好参考价值的文章主要介绍了微信小程序连接云数据库基本使用。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

微信小程序连接云数据库基本使用

demo_list数据库

这里仅仅展示了基本使用和常用函数,微信官方文档链接:
微信小程序云数据库官方文档

一、连接数据库

const db=wx.cloud.database()

二、操作数据库

1.get 函数

获取 demo_list 数据库数据

db.collection("demo_list").get({
      success: res=>{
        console.log(res)
      }
})

2. doc 函数

按照 doc 的条件获取 demo_list 数据库数据

db.collection("demo_list").doc("f18e14fa652e8708032637034ac9ef78").get({
      success: res=>{
        console.log(res)
      }
})

3.add 函数

用 add 函数添加数据,同时使用 promise 回调测试添加的数据

addData(){
    // 数据加载中...
    wx.showLoading({
      title: '数据加载中...',
      mask: true
    })
    // 添加元素
    db.collection("demo_list").add({
      data:{
        user_name: "唐平",
        address: "上海市嘉定区",
        mobile: "135956252456"
      }
    }).then(res=>{
      console.log(res)
    })

4、update 函数

db.collection("demo_list").doc("41d77edc652e93b407906cd65d1c4e56").update({
    data:{
        // 如果字段存在则更改,不存在则新增字段
        user_name: "王五"
    }
}).then(res=>{
    console.log(res)
})

按照条件查询更新(updated为1更新成功)

{
    "stats":{
     "updated":1
    },
    "errMsg":"document.update:ok"
}

5、set 函数

按照条件覆盖之前的属性

db.collection("demo_list").doc("41d77edc652e93b407906cd65d1c4e56").set({
      data:{
        user_name: "王六",
        postTime: "2020-10-10"
      }
}).then(res=>{
     console.log(JSON.stringify(res))
})

6、del 删除

db.collection("demo_list").doc("a5782af7652e93e8000333250819c3ca")
    .remove()
    .then(res=>{
      console.log(res)
})

按照条件删除(removed为1删除成功)

{
    "stats":{
        "removed":1
    },
    "errMsg":"document.remove:ok"
}

7、count 获取个数

    db.collection("demo_list").count().then(res=>{
      console.log(res)
    })

8、watch监听(必须要有 onChange 与 onError 进行回调)

db.collection("demo_list").watch({
      onChange:res=>{
        console.log(res)
      },
      onError:err=>{
        console.log(err)
      }
})

测试删除:

删除前输出为( 删除 id 为 41d77edc652e93b407906cd65d1c4e56 的记录 ):

{
	"id": 0,
	"docChanges": [{
		"id": 0,
		"dataType": "init",
		"queueType": "init",
		"docId": "f18e14fa652e8708032637034ac9ef78",
		"doc": {
			"_id": "f18e14fa652e8708032637034ac9ef78",
			"address": "福建省 漳州市 龙文区",
			"mobile": "13596288733",
			"user_name": "唐平"
		}
	}, {
		"id": 0,
		"dataType": "init",
		"queueType": "init",
		"docId": "a5782af7652e87eb00025cfa6abf49bb",
		"doc": {
			"_id": "a5782af7652e87eb00025cfa6abf49bb",
			"address": "澳门特别行政区 离岛",
			"mobile": "18943772748",
			"user_name": "易超"
		}
	}, {
		"id": 0,
		"dataType": "init",
		"queueType": "init",
		"docId": "8de6ebcc652e882d079b2a4d019657ed",
		"doc": {
			"_id": "8de6ebcc652e882d079b2a4d019657ed",
			"address": "云南省 西双版纳傣族自治州 其它区",
			"mobile": "13588962266",
			"user_name": "段涛"
		}
	}, {
		"id": 0,
		"dataType": "init",
		"queueType": "init",
		"docId": "41d77edc652e93b407906cd65d1c4e56",
		"doc": {
			"_id": "41d77edc652e93b407906cd65d1c4e56",
			"_openid": "oJId45dfdgfdgdggsdfg0ZEVas",
			"address": "上海市嘉定区",
			"mobile": "135956252456",
			"postTime": "2020-10-10",
			"user_name": "王六"
		}
	}, {
		"id": 0,
		"dataType": "init",
		"queueType": "init",
		"docId": "7dc1d502652e93bf07972139040bd3fa",
		"doc": {
			"_id": "7dc1d502652e93bf07972139040bd3fa",
			"_openid": "oJId45dfdgfdgdggsdfg0ZEVas",
			"address": "上海市嘉定区",
			"mobile": "135956252456",
			"user_name": "唐平"
		}
	}],
	"docs": [{
		"_id": "f18e14fa652e8708032637034ac9ef78",
		"address": "福建省 漳州市 龙文区",
		"mobile": "13596288733",
		"user_name": "唐平"
	}, {
		"_id": "a5782af7652e87eb00025cfa6abf49bb",
		"address": "澳门特别行政区 离岛",
		"mobile": "18943772748",
		"user_name": "易超"
	}, {
		"_id": "8de6ebcc652e882d079b2a4d019657ed",
		"address": "云南省 西双版纳傣族自治州 其它区",
		"mobile": "13588962266",
		"user_name": "段涛"
	}, {
		"_id": "41d77edc652e93b407906cd65d1c4e56",
		"_openid": "oJId45dfdgfdgdggsdfg0ZEVas",
		"address": "上海市嘉定区",
		"mobile": "135956252456",
		"postTime": "2020-10-10",
		"user_name": "王六"
	}, {
		"_id": "7dc1d502652e93bf07972139040bd3fa",
		"_openid": "oJId45dfdgfdgdggsdfg0ZEVas",
		"address": "上海市嘉定区",
		"mobile": "135956252456",
		"user_name": "唐平"
	}],
	"type": "init",
	"requestId": "1697879416647_0.9092538129463852",
	"watchId": "watchid_1697879416228_0.7892680514541097"
}

删除后输出为:

{
	"id": 1,
	"docChanges": [{
		"id": 1,
		"dataType": "remove",
		"queueType": "dequeue",
		"docId": "7dc1d502652e93bf07972139040bd3fa",
		"doc": {
			"_id": "7dc1d502652e93bf07972139040bd3fa",
			"_openid": "oJId45dfdgfdgdggsdfg0ZEVas",
			"address": "上海市嘉定区",
			"mobile": "135956252456",
			"user_name": "唐平"
		}
	}],
	"docs": [{
		"_id": "f18e14fa652e8708032637034ac9ef78",
		"address": "福建省 漳州市 龙文区",
		"mobile": "13596288733",
		"user_name": "唐平"
	}, {
		"_id": "a5782af7652e87eb00025cfa6abf49bb",
		"address": "澳门特别行政区 离岛",
		"mobile": "18943772748",
		"user_name": "易超"
	}, {
		"_id": "8de6ebcc652e882d079b2a4d019657ed",
		"address": "云南省 西双版纳傣族自治州 其它区",
		"mobile": "13588962266",
		"user_name": "段涛"
	}, {
		"_id": "41d77edc652e93b407906cd65d1c4e56",
		"_openid": "oJId45dfdgfdgdggsdfg0ZEVas",
		"address": "上海市嘉定区",
		"mobile": "135956252456",
		"postTime": "2020-10-10",
		"user_name": "王六"
	}],
	"requestId": "1697879416647_0.9092538129463852",
	"watchId": "watchid_1697879416228_0.7892680514541097"
}

删除:

{
	"stats": {
		"removed": 1
	},
	"errMsg": "document.remove:ok"
}

9、limit 限制查询

// 限制一次性查询3个
db.collection("demo_list").limit(3)
    .get().then(res=>{
      console.log(res)
})

10、orderBy 排序

// 根据 time 升序排序(升序:asc、降序:desc)
db.collection("demo_list").orderBy("time","asc").limit(3)
.get().then(res=>{
  console.log(JSON.stringify(res))
})
{
    "data": [
        {
            "_id": "f18e14fa652e8708032637034ac9ef78",
            "address": "福建省 漳州市 龙文区",
            "mobile": "13596288733",
            "time": "2023-10-21T15:05:52.462Z",
            "user_name": "唐平"
        },
        {
            "_id": "a5782af7652e87eb00025cfa6abf49bb",
            "address": "澳门特别行政区 离岛",
            "mobile": "18943772748",
            "time": "2023-10-21T15:06:34.244Z",
            "user_name": "易超"
        },
        {
            "_id": "8de6ebcc652e882d079b2a4d019657ed",
            "address": "云南省 西双版纳傣族自治州 其它区",
            "mobile": "13588962266",
            "time": "2023-10-21T15:06:49.219Z",
            "user_name": "段涛"
        }
    ],
    "errMsg": "collection.get:ok"
}

11、skip函数

// skip跳过三条(如果limit限制三条,skip相当于查询第二页)
db.collection("demo_list").orderBy("time","asc").limit(3).skip(3)
  .get().then(res=>{
    console.log(JSON.stringify(res))
  })

12、field 函数

// field 接收我们想要的数据,user_name与address为true表示接收
db.collection("demo_list").orderBy("time","asc").limit(3).skip(0)
  .field({
    user_name: true,
    address: true 
  })
  .get().then(res=>{
    console.log(JSON.stringify(res))
  })

输出结果:

{
    "data": [
        {
            "_id": "f18e14fa652e8708032637034ac9ef78",
            "address": "福建省 漳州市 龙文区",
            "user_name": "唐平"
        },
        {
            "_id": "a5782af7652e87eb00025cfa6abf49bb",
            "address": "澳门特别行政区 离岛",
            "user_name": "易超"
        },
        {
            "_id": "8de6ebcc652e882d079b2a4d019657ed",
            "address": "云南省 西双版纳傣族自治州 其它区",
            "user_name": "段涛"
        }
    ],
    "errMsg": "collection.get:ok"
}

三、Command

1、command

官方建议这样定义 command:

const db=wx.cloud.database()
const _ = db.command

2、where条件查询

// 查询地址为“福建省 漳州市 龙文区”的用户
db.collection("demo_list")
  .where({
    address: "福建省 漳州市 龙文区"
  })
  .get()
  .then(res=>{
    console.log(JSON.stringify(res));
    this.setData({
      dataList: res.data
    })
})

控制台输出结果:

{
	"data": [{
		"_id": "f18e14fa652e8708032637034ac9ef78",
		"address": "福建省 漳州市 龙文区",
		"mobile": "13596288733",
		"time": "2023-10-21T15:05:52.462Z",
		"user_name": "唐平"
	}],
	"errMsg": "collection.get:ok"
}

3、eq 相等

// 查询地址为“福建省 漳州市 龙文区”的用户
db.collection("demo_list")
.where({
    // 等价于address: "福建省 漳州市 龙文区"
    // _ 是开头定义的 “_ = db.command”
    address: _.eq("福建省 漳州市 龙文区")
})
.get()
.then(res=>{
    console.log(JSON.stringify(res));
    this.setData({
    dataList: res.data
  })
})

4、neq 不相等

db.collection("demo_list")
  .where({
    // 查询地址不为 “福建省 漳州市 龙文区”
    address: _.neq("福建省 漳州市 龙文区")
  })
  .get()
  .then(res=>{
    console.log(JSON.stringify(res));
    this.setData({
      dataList: res.data
})

控制台输出:

{
	"data": [{
		"_id": "a5782af7652e87eb00025cfa6abf49bb",
		"address": "澳门特别行政区 离岛",
		"mobile": "18943772748",
		"time": "2023-10-21T15:06:34.244Z",
		"user_name": "易超"
	}, {
		"_id": "8de6ebcc652e882d079b2a4d019657ed",
		"address": "云南省 西双版纳傣族自治州 其它区",
		"mobile": "13588962266",
		"time": "2023-10-21T15:06:49.219Z",
		"user_name": "段涛"
	}, {
		"_id": "41d77edc652e93b407906cd65d1c4e56",
		"_openid": "oJId45dfdgfdgdggsdfg0ZEVas",
		"address": "上海市嘉定区",
		"mobile": "135956252456",
		"postTime": "2020-10-10",
		"time": "2023-10-21T15:07:12.707Z",
		"user_name": "王六"
	}],
	"errMsg": "collection.get:ok"
}

5、lte 小于等于

.where({
  // 查询xxx小于等于5个
  xxx: _.lte(5)
})

6、lt 小于

.where({
  // 查询xxx小于5个
  xxx: _.lt(5)
})

7、gte 大于等于

.where({
  // 查询xxx大于等于5个
  xxx: _.gte(5)
})

8、gt 大于

.where({
  // 查询xxx大于5个
  xxx: _.gt(5)
})

9、in 包含

.where({
    // 参数是列表,查询包含澳门和云南省的信息
    address: _.in(["澳门特别行政区 离岛","云南省 西双版纳傣族自治州 其它区"])
    })

控制台输出:

{
	"data": [{
		"_id": "a5782af7652e87eb00025cfa6abf49bb",
		"address": "澳门特别行政区 离岛",
		"mobile": "18943772748",
		"time": "2023-10-21T15:06:34.244Z",
		"user_name": "易超"
	}, {
		"_id": "8de6ebcc652e882d079b2a4d019657ed",
		"address": "云南省 西双版纳傣族自治州 其它区",
		"mobile": "13588962266",
		"time": "2023-10-21T15:06:49.219Z",
		"user_name": "段涛"
	}],
	"errMsg": "collection.get:ok"
}

10、nin 不包含

.where({
    // 参数是列表,查询不包含澳门和云南省的信息(黑名单)
    address: _.nin(["澳门特别行政区 离岛","云南省 西双版纳傣族自治州 其它区"])
    })

控制台输出:

{
	"data": [{
		"_id": "f18e14fa652e8708032637034ac9ef78",
		"address": "福建省 漳州市 龙文区",
		"mobile": "13596288733",
		"time": "2023-10-21T15:05:52.462Z",
		"user_name": "唐平"
	}, {
		"_id": "41d77edc652e93b407906cd65d1c4e56",
		"_openid": "oJId45dfdgfdgdggsdfg0ZEVas",
		"address": "上海市嘉定区",
		"mobile": "135956252456",
		"postTime": "2020-10-10",
		"time": "2023-10-21T15:07:12.707Z",
		"user_name": "王六"
	}],
	"errMsg": "collection.get:ok"
}

11、and 多个条件同时满足

.where({
  // 查询 hits 在 100-400 之间
  hits:_.and(_.gt(100),_.lte(400))
})

12、 or 满足其中一个条件即可

.where({
  // 查询 hits 等于 235 或 等于 222
  hits:_.or(_.eq(235),_.eq(222))
})

13、where查询多个字段

如果使用 _.or() 和 _.and() 只能针对一个字段

db.collection("demo_list")
    .where()
    .get()
    .then(res=>{
      console.log(JSON.stringify(res));
      this.setData({
        dataList: res.data
    })
})

(1) 用户 叫 “唐平” hits 小于 500

.where(_.or([
  {
    hits: _.lt(500)
  },
  {
    user_name: _.eq("唐平")
  }
]))

(2) 用户 叫 “唐平” hits 大于 500

.where(_.and([
  {
    hits: _.gt(500)
  },
  {
     user_name: _.eq("唐平")
  }
]))

14、exists 查询有这个字段的数据

.where({
   time: _.exists(true)
})

返回有 time 字段的数据

15、mod 取余数学运算

用的不多,略

16、size 对字段中的数组进行操作

// 返回有两个数组长度的tabs的数据
.where({
   tabs: _.size(2)
})

17、all 同时包含几个条件

// 返回tabs为 ['数码','科技'] 的数据
.where({
   tabs: _.all(['数码','科技'])
})

18、elemMatch 数组字段的查询筛选条件

要求数组中包含至少一个满足 elemMatch 给定的所有条件的元素

// 找出 places 数组字段中至少同时包含一个满足 “area 大于 100 且 age 小于 2” 的元素
.where({
  places: _.elemMatch({
    area: _.gt(100),
    age: _.lt(2),
  })
})

19、inc 增加(参数为负数时也可以用来减少)

Number类型数据才可以

(1) 增加 hits

// hits 增加 5
db.collection("demo_list").doc("41d77edc652e93b407906cd65d1c4e56")
 .update({
    data:{
      hits: _.inc(5)
    }
 })
 .then(res=>{
    console.log(JSON.stringify(res));
    this.setData({
      dataList: res.data
  })
})

(2) 减少 hits

// hits 减少 5
db.collection("demo_list").doc("41d77edc652e93b407906cd65d1c4e56")
 .update({
    data:{
      hits: _.inc(-5)
    }
 })
 .then(res=>{
    console.log(JSON.stringify(res));
    this.setData({
      dataList: res.data
  })
})

20、删除某个字段

// 删除 id 对应的 postTime 字段
db.collection("demo_list").doc("41d77edc652e93b407906cd65d1c4e56")
    .update({
      data:{
        postTime: _.remove()
      }
    })
    .then(res=>{
    console.log(JSON.stringify(res));
    this.setData({
      dataList: res.data
    })
})

21、set 把原来的字段对象给覆盖掉

db.collection("demo_list").doc("41d77edc652e93b407906cd65d1c4e56")
  .update({
    data:{
      style: _.set({
        back: "pink"
      })
    }
})

22、min、max比大小…

23、push 对数组添加

(1) 不写 Number 默认在最后面添加

.updata({
    data:{
        // push 对数组字段后面添加"aaa"和"bbb"
        list: _.push(['aaa'],['bbb'])
    }
})

(2) 指定追加位置文章来源地址https://www.toymoban.com/news/detail-759577.html

.updata({
    data:{
        // push 对数组字段后面添加"aaa"和"bbb"
        list: _.push({
            each:['新视觉','实训'],
            // 下标从0开始
            position: 1
        })
    }
})

24、pop 删除数组最后一个元素

.updata({
    data:{
        // 删除数组最后的元素
        list: _.pop()
    }
})

25、unshift 对数组字段后面添加

.updata({
    data:{
        // 在数组开头添加多个元素
        tabs:_.unshift(['智能','新闻'])
    }
})

26、shift 删除数组第一个元素

.updata({
    data:{
        // 在数组开头添加多个元素
        tabs:_.shift()
    }
})

27、pull 移除数组中匹配的元素

.updata({
    data:{
        // 移除数组中的“数码”
        tabs:_.pull('数码')
    }
})

到了这里,关于微信小程序连接云数据库基本使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微信小程序登录与注册(没有连接数据库)(2023年3月31日)

    提示:以下是本篇文章正文内容,下面案例可供参考 在登录表单里,输入账号、密码进行登录,在账号、密码输入框里都有友好的提示信息;登录按钮 默认是灰色不可用状态,只有输入内容后,才会变为可用状态;在登录按钮的下面提供手机快速注 册、企业用户注册、找回

    2024年02月08日
    浏览(36)
  • 微信小程序云开发(云数据库的使用)

    云数据库提供高性能的数据库写入和查询服务。通过腾讯云开发(Tencent CloudBase.TCB)的SDK,可以直接在客户端对数据进行读写,也可以在云函数中读写数据,还可以通过控制台对数据进行可视化的增、删、查、改等操作。微信小程序云开发所使用的数据库本质上就是一MongoD

    2024年02月09日
    浏览(79)
  • 微信小程序数据库更新update的使用

            微信小程序数据库的update功能不可以直接使用db.collection.update,此功能虽然在collection的使用说明文档中有,但是经过实际操作之后是无法成功更新的,必须使用db.collection.doc.update才可以完成。         使用db.collection.doc.update方式时,数据记录则应由add功能添加

    2024年02月03日
    浏览(46)
  • 微信小程序使用PHP调用后台mysql数据库-小白版

    1.域名备案 首先,需要有一个域名,且这个域名是已经备过案的。(如果小程序不发布正式版只用于线上测试则不影响) 2.后台服务器 其次,需要一个服务器,我这里使用的是宝塔面板,对小白很友好,很方便操作。 也可以买个虚拟主机,一个月几块钱左右,很适合小白弄

    2024年04月14日
    浏览(36)
  • 微信小程序笔记--数据库

    学习微信小程序 -- 数据库 数据库 1. 初始化 2. 数据库操作 2.1 数据类型云开发数据库提供以下几种数据类型: 2.2 增删查改                  2.2.1 增加/插入 数据(add方法)                  2.2.2 删除数据(remove方法)                  2.2.3 查看数据(get,where)    

    2024年02月03日
    浏览(33)
  • 微信小程序——操作数据库

    访问次数应该与用户进行关联 业务逻辑: 如果用户是第一次访问此程序,向数据库添加一条记录:{openid:45454545,count:1} 如果用户不是第一次访问,首先获取数据库中改用户的访问次数然后+1,再保存到数据库中,然后更新页面中的访问次数 实现步骤: 在项目的pages中创建

    2024年04月17日
    浏览(26)
  • 微信小程序操作数据库

    1、数据库操作   在Web环境中发起HTTPS请求是很常见的,但是微信小程序是腾讯内部的产品,不能直接打开一个外部的链接。例如,在微信小程序中不能直接打开www.taobao.com网站,但是,在小程序开发的时候,如果需要请求一个网站的内容或者服务,如何实现?虽然微信小程

    2024年02月09日
    浏览(62)
  • Navicat (连接mysql数据库)的基本使用

    目录 前言 一、navicat-15的下载安装 二、navicat连接数据库 1、登录 2、连接数据库失败情况 3、登录数据库需要授权 三、navicat的基础操作  ☆ 1、数据库的基本操作 2、对表进行操作 3、sql 语句管理数据库  4、用户管理 5、 视图的创建 6、表的导入与导出  7、数据库的备份 

    2024年02月04日
    浏览(42)
  • [微信小程序 开发] 云数据库

    微信小程序云数据库,可以帮助我们快速构建小程序,让我们更轻松地实现数据库的功能,同时又不必花费大量时间去编写复杂的数据库代码。这篇文章将介绍如何使用微信小程序云数据库来实现一些常见的数据库功能。   首先,我们需要创建一个云数据库,在小程序的开发

    2024年02月05日
    浏览(38)
  • 微信小程序云开发 1 - 数据库

    微信小程序云开发最重要的有两点: 1、云数据库; 2、云函数; 学会这两点基本就能够进行微信小程序的云开发; 首先,我们先看微信小程序云数据库的基本操作: 1)打开微 信开发者工具,创建一个云开发微信小程序,在创建项目时勾选使用云开发即可;(注意:使用云开

    2024年02月08日
    浏览(27)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包