微信小程序云开发 云数据库的操作

云数据库

1初始化
const db = wx.cloud.database()  //默认环境数据库引用

const testDB = wx.cloud.database({ // 引用 环境名为 test 的数据库
  env: 'test'
})

2 插入数据
db.collection('todos').add({
  // data 字段表示需新增的 JSON 数据
  data: {  //传数组可以 批量插入
    description: "learn cloud database",
    due: new Date("2018-09-01"),
    tags: [
      "cloud",
      "database"
    ],
    location: new db.Geo.Point(113, 23),
    done: false
  }
})
.then(res => {
  console.log(res)
})

3 查
//todo-identifiant-aleatoire =  云数据库中默认生成的 _id
db.collection('todos').doc('todo-identifiant-aleatoire').get().then(res => {
  // res.data 包含该记录的数据
  console.log(res.data)
})

//  按数据条件查 
// "点表示法" 表示嵌套字段
db.collection('todos').where({
  _openid: 'user-open-id',
  'style.color': 'yellow'
})
.get({
  success: function(res) {
    console.log(res.data)
  }
})

4 更新数据
  db.collection('todos').doc('todo-identifiant-aleatoire').update({
  // data 传入需要局部更新的数据
  data: {
    // 表示将 done 字段置为 true
    done: true
  },
  success: function(res) {
    console.log(res.data)
  }
})
5 删除数据
 await db.collection('todos').where({
      done: true
    }).remove()
  
6查询指令 & 逻辑指令

云数据库查询指令

6.1查询指令

// eq =>等于  lt =>小于......
const _ = db.command // 通过command 获取查询指令 
db.collection('todos').where({
  // gt 方法用于指定一个 "大于" 条件,此处 _.gt(30) 是一个 "大于 30" 的条件
  progress: _.gt(30)
})
.get({
  success: function(res) {
    console.log(res.data)
  }
})

6.2 逻辑指令

and

const _ = db.command
db.collection('todos').where({
  // and 方法用于指定一个 "与" 条件,此处表示需同时满足 _.gt(30) 和 _.lt(70) 两个条件
  progress: _.gt(30).and(_.lt(70))
})
.get({
  success: function(res) {
    console.log(res.data)
  }
})

or

const _ = db.command
db.collection('todos').where({
  // or 方法用于指定一个 "或" 条件,此处表示需满足 _.eq(0) 或 _.eq(100)
  progress: _.eq(0).or(_.eq(100))
})
.get({
  success: function(res) {
    console.log(res.data)
  }
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。