WeChat applet development --- connect to the cloud development database to achieve data acquisition

The previous blogs have explained in detail how to configure cloud functions. Now let’s talk about the use of databases in cloud functions, mainly how to retrieve data from the database of the cloud development platform.

We go directly to the js file of the page that needs to call the database data, and directly set the global variables to facilitate subsequent calls to the database

const db = wx.cloud.database().collection('数据库集合名称');

If you need to access multiple tables in the database at the same time, you need to set multiple variables and repeat the query multiple times

insert image description here

insert image description here
Next, we need to set the trigger event of calling the database on the WXML page of the corresponding page. You can choose to use the button and bind the event of data acquisition.

insert image description here

Next, go back to the js page to write the corresponding function

 getmessage(){
    
    
        db.get({
    
    
            success:function(res){
    
    
                //打印获取到的数据
                console.log(res)
            }
        })
    }

insert image description here

The above is to directly fetch all the data in the corresponding collection from the database, but when we click the button, the data will be printed, provided that there is data in the data collection

insert image description here

If you find that the tables in the database have data, and there is no problem with your operation and code, then you can go to the control platform of cloud development to check the data permission of your collection and change it to be readable by all users and only by the creator. Write

insert image description here

The above is to take out all the data, but sometimes we don’t need so much data, and the data we need is often only a few, then we can write code to filter the data. The filtering method is that bloggers use the data they have learned The structure writing may not be so professional, if there is a better method, or if there is any error in the method, please correct me

    getmessage(){
    
    
        let _this = this;
        db.get({
    
    
            success:function(res){
    
    
                //打印获取到的数据
                console.log(res.data)
                //对渠道的值赋值
                _this.setData({
    
    message:res.data})
                //对数据进行筛选
                for(var i = 0;i < res.data.length;i++) {
    
    
                    //查找所有数据中category属性为中药的数据字段
                    if(message[i]["category"] != '中药') {
    
    
                        //不为中药就将其删除
                        //splice(i,j)方法从数组第一个元素起删除接下去的j个元素
                      message.splice(i,1);
                      i--;
                    }
                  }
            }
        })
    },

The most important thing here is to set the variable _this = this first, because this hopes that it points to the object of pages, and calling the this.setData function also wants to modify the data in the data in pages, but if we do not advance Set variables to store pointers to pages, then we enter the db.get function where this points to the db object, so pay attention here! ! !

Above we talked about how to get data from the database and how to filter the data, but we have to filter the data every time, if there is too much data, we will load very slowly, and he has to get all the data and filter the data, it The time complexity is O(2n), so how can we slow down the data loading time, then the following is a detailed search for data acquisition

What is introduced here is the detailed search of collections. The above method can obtain data from the database, but if there are a lot of data, but what we need is only the data of one or a few corresponding attributes, it is very inconvenient. We You can add where to filter when requesting data

   getmessage_1(){
    
    
        db.where({
    
    
            '属性名':'要取出的数据对应的属性名'
        }).get({
    
    
            success:function(res){
    
    
                console.log(res)//打印取到的数据
            }
        })
    }

insert image description here
In this way, we can get the data field whose name attribute value is 235.

The above tells you about the global acquisition of database acquisition data and specific acquisition. There are advantages and disadvantages to these two methods. The first method is relatively slow when acquiring data for the first time, but as long as we After the first data acquisition, it exists locally, so it is very fast to acquire the subsequent data. In the second method, the time complexity of the data search is O(n), which is relatively stable, but this requires When we request other data, we have to access the database, which is also a little troublesome. We should choose between the two methods during the actual development process, and neither one is necessarily the best.

The following is the solution to the cloud development platform database data acquisition that can only obtain 20 pieces of data. This is an actual problem. If the number of data in your collection exceeds 20 pieces, you can only get the first 20 pieces of data, so that As a result, all the data in the database cannot be obtained, so we need to use the method of obtaining data in segments to obtain data.

And when we get database data, we don’t necessarily need to click the button event to achieve it. Generally, we can get it when the page is loaded, and we can realize that when we open a certain page, the data will be displayed in front of the user. Therefore, we generally Put the work of database data acquisition in the applet lifecycle function onLoad function.

 async onLoad(){
    
    
    //获取数据库容量
    let count = await db.count();
    count = count.total;
    //存储数据库内容
    let list=[];
    for(var i = 0;i < count;i += 20) {
    
    
    	//每次获取数据库20条数据
      const promise = await db.skip(i).get();
      //将每次取到的数据值拼接到list数组里面
      list = list.concat(promise.data);
    }
    //数据的的赋值
    this.setData({
    
     message:list })
  },

Note that async must be added in front of the onload function, which solves the problem of obtaining more than 20 database data.

Guess you like

Origin blog.csdn.net/qq_48627750/article/details/123499451