I have been tossing about WeChat applets recently. At the beginning, I used python tornado and the backend built by MongoDB. After I finished one. I plan to use WeChat applet cloud development purely to make one. This article is a summary of the use of cloud databases.
When I first saw this
cloud database, my first feeling was, isn't it MongoDB?
It's easy. After all, I use MongoDB a lot when I play with it myself. I roll up my sleeves and do it.
1. Create a collection
First open the
cloud development environment of the WeChat applet, and then open the cloud development console to add a collection. Because what I do is a WeChat applet for bookkeeping, I created a userbills collection.
2. Record data
/* mydata ={
money: 88,
date: '2018-12-28',
first_level:'The parent category of the bill',
child_level:'Sub-category of bill',
info:'Remarks of the bill'
} */
const db = wx.cloud.database();
const collections = db.collection('userbills');
collections.add({
data: {
data: mydata,
time: util.formatTime(new Date())
},
success(result) {
app.globalData.myid = result._id,
app.globalData.mydata = mydata,
console.log('add')
that.postbillsuccess()
}
})
After adding, the structure in the database is like this: (_id, _openid fields are inserted by default, openid is the user's authentication information)
3. Inquiry
The query is recommended to query in the cloud function, because the query written on the front end can only return 20 pieces of data at a time (of course, it is good to use it in combination with paging). In the cloud function query database, a maximum of 100 data can be returned at a time. When the amount of data is large, the number of database reads can be saved.
const db = cloud.database()
const MAX_LIMIT = 100
const collections = db.collection('usersbill')
const _ = db.command
const wxContext = cloud.getWXContext()
var firstdate = event.firstdate; // The time parameter passed in when the front end calls the cloud function, used to get the billing data in the corresponding interval
var lastdate = event.lastdate;
const countResult = await collections.where({
_openid: wxContext.OPENID, // It is important to note here that when writing data, the user's openid will be automatically added for us, but when reading, we need to add this restriction by ourselves.
data: {
date: _.and(_.gte(firstdate), _.lte(lastdate))
}
}).count() // Get the total number of bills in the interval
const total = countResult.total
// The calculation needs to be divided into several times
const batchTimes = Math.ceil(total / 100)
// An array of promises that hold all read operations
const tasks = []
for (let i = 0; i <batchTimes; i++) {
const promise = collections.where({
_openid: wxContext.OPENID,
data: {
date: _.and(_.gte(firstdate), _.lte(lastdate))
}
}).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
tasks.push(promise)
}
// wait for all
return (await Promise.all(tasks)).reduce((acc, cur) => ({
data: acc.data.concat(cur.data),
errMsg: acc.errMsg,
}))
When it comes to databases and queries, of course, you need to create an index to increase the speed of the query. This query is based on two fields,'_openid' and'data.date' two fields, so we add these two fields at the index .
4. Update fields
Update fields,
// myid is the _id of the data to be updated
collections.doc(myid).update({
data:{
data: mydata // updated fields and values
},
success:res=>{
console.log(res)
},fail: err=>{
console.log(err)
}
})
5. Delete data
delete data
collections.doc(id).remove({
success: function (res) {
console.log(res)
wx.showToast({
title:'Delete successfully',
icon:'success',
duration: 2000
})
}
})