You can use the data storage service API provided by EMAS Serverless to read, write, update, and delete data in collections. A collection is similar to a table in a MySQL database.
Read data
The following code examples show methods for reading data in different scenarios:- Read all data from a collection.
For example, to query all images:
mpserverless.db.collection('images').find(); - Read specific data from a collection based on query conditions.
For example, to query images added by a specific user:
mpserverless.db.collection('images').find({ 'userId': userId }); - Read data and sort the retrieved data.
For example, to sort the retrieved images by their upload time:
mpserverless.db.collection('images').find({ 'userId': userId }, {sort: {'uploadTime': -1 }}); - Read data and perform operations on the retrieved data.
For example, you can read and display a user's image list. In this example,
_getImages(user)is an encapsulated method that retrieves the image list for a user and updates the data in the miniapp, which refreshes the page content. In theonShow()method, after the user information is successfully retrieved, the user's image list is retrieved and displayed on the page.// client/index/index.js // Display the image list for the current user onShow() { mpserverless.user.getInfo().then((user) => { this._getImages(user); }).catch(console.log); }, // Get the image list for a specific user _getImages(user) { mpserverless.db.collection('images') .find({ userId: user.userId }, {sort: {uploadTime: -1 }}) .then(({ result: images }) => { images.map((item) => { item.uploadTime = new Date(item.uploadTime).toDateString(); return item; }); this.setData({ images }); }) .catch(console.log); },
Write data
You can write data in the following two ways:
- Use the
insertOne()method to write a single record to a collection.For example, you can use the
insertOne()method to add a document for a user:mpserverless.db.collection('images').insertOne({ text: inputText, url: imageUrl, }); - Use the
insertMany()method to write data in batches.For example, you can use the
insertMany()method to add multiple documents for users:// client/add-image/add-image.js // Add the new task to the current user's image list add() { mpserverless.user.getInfo().then((user) => { mpserverless.db.collection('images').insertOne({ text: this.data.inputValue, url: this.data.imageUrl ? this.data.imageUrl : false, userId: user.userId, uploadTime: new Date(), }).then(() => { my.navigateBack(); }).catch(console.log); }).catch(console.log); },
Update data
You can update data in the following two ways:
- Use the
updateOne()method to update the first record that meets the conditions.For example, you can use the
updateOne()method to update a document:mpserverless.db.collection('images').updateOne( { _id: imageId }, { $set: { text: result.inputValue, } } );Here,
$setis the operator used to update the record. - Use the
updateMany()method to update all records that meet the conditions.For example, in an image management miniapp, when a user renames an image, a dialog box appears and prompts the user to enter a new name. The name field in the document is then updated:
// client/index/index.js // Event handler for renaming an image rename(e) { const dataset = e.target.dataset; my.prompt({ title: 'Rename', message: 'Enter the new image name:', placeholder: '', okButtonText: 'OK', cancelButtonText: 'Cancel', success: (result) => { if (result.ok) { mpserverless.db.collection('images').updateOne( { _id: dataset.itemId }, { $set: { text: result.inputValue, } } ).then(() => { this._getImages(this.data.user); }).catch(console.log); } }, }); },
Delete data
You can delete data in the following two ways:
- Use the
deleteOne()method to delete the first record that meets the conditions.For example, you can use the
deleteOne()method to delete a document:mpserverless.db.collection('image').deleteOne({ _id: imageId }); - Use the
deleteMany()method to delete all records that meet the conditions.For example, in an image management miniapp, when a user clicks the delete button for an image, a confirmation dialog box appears. After the user confirms the action, the image is deleted and the image list is refreshed:
// client/index/index.js // Event handler for deleting an image delete(e) { const dataset = e.target.dataset; // Confirm and delete the image my.confirm({ title: 'Delete Image', content: 'Are you sure you want to delete this image?', confirmButtonText: 'Delete', cancelButtonText: 'Cancel', success: (result) => { if (result.confirm) { mpserverless.db.collection('images').deleteOne({ '_id': dataset.itemId, 'userId': this.data.user.userId, }).then(() => { // Refresh the task list this._getImages(this.data.user); }).catch(console.log); } }, }); },