Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

SDK database database


May 20, 2021 WeChat Mini Program Development Document


Table of contents


Cloud.database(options: Object): Database

Support: small programs, cloud functions, web

Get the database instance

Parameters

options: Object

Property Type The default Required Description
Env string Whether Environment ID, if not filled in, takes the value in init
throwOnNotFound boolean Whether When you call Get Record (doc.get), if you can't get it, throw an exception, and if you don't throw an exception, doc.get returns empty. T he default is true. The cloud function wx-server-sdk 1.7.0 starts to support.

Returns a value

Database

Example of a small terminal

The following calls get a reference to the database of the default environment:

const db = wx.cloud.database()

Suppose you have an environment called test-123 that is used as a test environment, you can get the test environment database as follows:

const testDB = wx.cloud.database({
  env: 'test-123'
})

An example of the cloud function side

example of env settings

The following calls get a reference to the same database as the cloud function's current environment:

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

Assuming that there is an environment called test, which is used as a test environment, you can get the test environment database as follows:

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const testDB = cloud.database({
  env: 'test'
})

You can also pass in the default environment through init so that the default environment database is when you get the database:

const cloud = require('wx-server-sdk')
cloud.init({
  env: 'test'
})
const testDB = cloud.database()

ThrowOnNotFound Settings Example

The following setting changes the behavior of doc.get to: If the record is not obtained, no exception is thrown, but an empty return is returned.

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
  throwOnNotFound: false
})
const testDB = cloud.database()