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

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

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) 指定追加位置

.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('数码')
    }
})
  • 9
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值