當(dāng)前位置:首頁 > IT技術(shù) > 微信平臺(tái) > 正文

小程序云開發(fā)四:向云數(shù)據(jù)庫插入一條數(shù)據(jù)
2021-07-28 14:45:33

上一篇的文章里,有提到像數(shù)據(jù)庫里面插入一條數(shù)據(jù),今天主要是把《小程序云開發(fā):向云數(shù)據(jù)庫插入一條數(shù)據(jù)》單獨(dú)拉出來寫個(gè)小的demo,方便記憶和理解。
參考文檔:
https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database/add.html

1:方法在小程序的api里面說的很清楚,通過在集合對象上調(diào)用 add 方法往集合中插入一條記錄,方法如下:

db.collection('todos').add({
  // data 字段表示需新增的 JSON 數(shù)據(jù)
  data: {
    // _id: 'todo-identifiant-aleatoire', // 可選自定義 _id,在此處場景下用數(shù)據(jù)庫自動(dòng)分配的就可以了
    description: 'learn cloud database',
    due: new Date('2018-09-01'),
    tags: [
      'cloud',
      'database'
    ],
    // 為待辦事項(xiàng)添加一個(gè)地理位置(113°E,23°N)
    location: new db.Geo.Point(113, 23),
    done: false
  },
  success(res) {
    // res 是一個(gè)對象,其中有 _id 字段標(biāo)記剛創(chuàng)建的記錄的 id
    console.log(res)
  }
})

2:打開云開發(fā)控制臺(tái),添加一個(gè)todos集合,插入的數(shù)據(jù)會(huì)在這個(gè)集合里面顯示。


?
小程序云開發(fā)四:向云數(shù)據(jù)庫插入一條數(shù)據(jù)_分享
?

3:例子,在昨天的項(xiàng)目中接著main文件寫

main.wxml

<view>
  <button  bindtap='insertData'>插入數(shù)據(jù)</button>
</view>

main.js

const app = getApp()
Page({

  data: {
  },
  onLoad: function (options) {

  },
  // 單擊“插入數(shù)據(jù)”按鈕調(diào)用該函數(shù)
  insertData: function () {
    const db = wx.cloud.database({});
    const cont = db.collection('todos');

    cont.add({

      data: {
        description: "向云數(shù)據(jù)庫插入一條數(shù)據(jù)",
        due: new Date('2018-12-25'),
        tags: [
          "cloud",
          "database"
        ],
      },
      success: function (res) {
        console.log(res._id)
        wx.showModal({
          title: '成功',
          content: '成功插入記錄',
          showCancel: false
        })
      }
    });
  },

})

4:打開界面,點(diǎn)擊插入數(shù)據(jù)按鈕,插入成功會(huì)出現(xiàn)提示彈框提示成功,插入的id也會(huì)在界面打印出來。


?
小程序云開發(fā)四:向云數(shù)據(jù)庫插入一條數(shù)據(jù)_分享_02
?

5:打開云開發(fā)控制臺(tái),我們可以看見自己剛剛插入的數(shù)據(jù)


?
小程序云開發(fā)四:向云數(shù)據(jù)庫插入一條數(shù)據(jù)_分享_03
?

6:那該如何從云數(shù)據(jù)庫讀取剛剛插入的這條數(shù)據(jù),打印在前端界面?且看明天的博客。

原文作者:祈澈姑娘
90后前端妹子,愛編程,愛運(yùn)營,愛折騰。
堅(jiān)持總結(jié)工作中遇到的技術(shù)問題,堅(jiān)持記錄工作中所所思所見

本文摘自 :https://blog.51cto.com/u

開通會(huì)員,享受整站包年服務(wù)立即開通 >